我试图从远程url中抓取一个图像,该url是使用高级自定义字段中的文本字段添加的(下面的示例中是硬编码的),但我甚至不知道我使用的过程是否正确。我阅读了多个源代码,但使用了不同的功能和技术(media\\u sideload\\u image、wp\\u remote\\u get等),所以我有点困惑。
我使用了多个源代码来创建以下代码。
从这里开始的刮刀(在以下示例中单独测试,工作正常):https://www.ostraining.com/blog/coding/extract-image-php/
我在这篇文章中使用了一些信息:https://stackoverflow.com/questions/31368072/error-in-fetching-image-using-wp-remote-get-function
以及文件:https://codex.wordpress.org/Function_Reference/media_handle_sideload
下面是我的代码:
function generate_featured() {
global $post;
if($update == false) {
if ( !function_exists(\'media_handle_upload\') ) {
require_once(ABSPATH . "wp-admin" . \'/includes/image.php\');
require_once(ABSPATH . "wp-admin" . \'/includes/file.php\');
require_once(ABSPATH . "wp-admin" . \'/includes/media.php\');
}
$url = \'https://www.google.gr\';
$html = file_get_contents($url);
preg_match_all( \'|<img.*?src=[\\\'"](.*?)[\\\'"].*?>|i\',$html, $matches );
$image_url = $url . $matches[1][0];
$tmp = download_url( $image_url );
$file_array = array(
\'name\' => $post_id . \'_\' . $image_url . \'_\' . basename( $matches[1][0] ),
\'tmp_name\' => $tmp
);
// Check for download errors
if ( is_wp_error( $tmp ) ) {
@unlink( $file_array[\'tmp_name\'] );
return false;
}
$id = media_handle_sideload( $file_array, $post_id );
// Check for handle sideload errors.
if ( is_wp_error( $id ) ) {
@unlink( $file_array[\'tmp_name\'] );
return false;
}
// Set post thumbnail.
set_post_thumbnail( $post_id, $id );
}
}
add_action( \'save_post\', \'generate_featured\', 10, 3 );
问题是我没有看到在wp-content/uploads
目录我暂时使用了media_sideload_image($file, $post_id, $desc);
函数和文件正确创建,但无法将其设置为特征图像。感谢您的帮助!