I am using
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 <a href="https://wordpress.stackexchange.com...age-url-when-using-wp-insert-post/41300#41300">this</a> 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).
<br>
When I go to image path using ftp, I can see image file but when I try to open image it says unsupported format.
<br>
Below is the code I used to fetch images
If I open image file with a text editor I am seeing something like below
Is there some error in encoding?<br>
Please Correct me what I am doing wrong.
Code:
wp_remote_get
<br>
When I go to image path using ftp, I can see image file but when I try to open image it says unsupported format.
<br>
Below is the code I used to fetch images
Code:
$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);
Code:
ArrayÿØÿà JFIF
Please Correct me what I am doing wrong.