I am using wp_remote_get
to fetch image from a url and attach it to a post as a Featured Image. I was able to do it initially using some help from this post and images were successfully set as featured image and are displaying in backend but now images are set as featured image successfully but only name of image is being displayed (as if the path of image file is broken).
When I go to image path using ftp, I can see image file but when I try to open image it says unsupported format.
Below is the code I used to fetch images
$upload_dir = wp_upload_dir();
$image_url = $one_post->images[0];
$image_data = wp_remote_get($image_url);
//Get image and set unique file name
$filename = $new_post_id."_".$one_post->ID."_".basename($image_url);
if (wp_mkdir_p($upload_dir['path'])) {
$file = $upload_dir['path'] . '/' . $filename;
} else {
$file = $upload_dir['basedir'] . '/' . $filename;
}
file_put_contents($file, $image_data);
$wp_filetype = wp_check_filetype($filename, null);
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name($filename),
'post_content' => '',
'post_status' => 'inherit',
);
$attach_id = wp_insert_attachment($attachment, $file, $new_post_id);
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata($attach_id, $file);
wp_update_attachment_metadata($attach_id, $attach_data);
set_post_thumbnail($new_post_id, $attach_id);
If I open image file with a text editor I am seeing something like below
ArrayÿÃÿà JFIF
Is there some error in encoding?
Please Correct me what I am doing wrong.
As I mentioned in my comment you’re seeing this issue because of the way you’re using
wp_remote_get()
andfile_put_contents()
.I also see that you’re duplicating some WordPress functionality. In my example below I’ve rewritten your code to take advantage of existing WordPress functions.
Based on the example given on the Codex page for
media_handle_sideload()
: https://codex.wordpress.org/Function_Reference/media_handle_sideload