I am trying to scrape an image from a remote url that is added using a text field in Advanced Custom Fields (hardcoded in the example below), but I don't even know if the process I am using is correct. I read multiple sources, but different functions and techniques are used (media_sideload_image, wp_remote_get, etc), so I am a bit confused.
I used multiple sources to create the following code.
The scraper from here (tested on its own for the following example, works just fine): https://www.ostraining.com/blog/coding/extract-image-php/
I used some info on this post: https://stackoverflow.com/questions/31368072/error-in-fetching-image-using-wp-remote-get-function
And the docs: https://codex.wordpress.org/Function_Reference/media_handle_sideload
So here is my code:
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 );
The thing is I don't see any files created on the wp-content/uploads
directory.
I temporarily used the media_sideload_image($file, $post_id, $desc);
function and the file gets created properly but cannot then set it as a featured image.
Any help is appreciated!
function
like this:function generate_featured( $post_id )
, then I commented out theglobal $post;
; and finally (although this is not mandatory..), in the$file_array
, I setname
like this:'name' => basename( $image_url ),
medium.com
. However, since multiple sites were supposed to be scraped, and didn't want to risk same errors, or maintaining each site/cdn separately, I took a different direction and decided to just save the fb meta image on each post and load it from its source directly. Also, please make your comment as an answer so I can give you credit for it.