I have uploaded some images to the wordpress media library. Now I am going to create some posts using php and want to use those already uploaded images as featured image for these posts respectively. How to set image as featured image for a post. I have tried below code. but it sets an empty image as featured image to posts.

function set_featured_image($post_id, $image_url){
global $wpdb;
$attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $image_url )); 
$image_attachment_id = $attachment[0];
$attachment = array(
    'ID' => $image_attachment_id,
    'post_parent' => $post_id

$attachement_id = wp_insert_attachment( $attachment );
set_post_thumbnail( $post_id, $attachement_id ); // also tried using $image_attachment_id but same issue 

I got this blank featured image

enter image description here

Prior thanks to any help.

  • Is the image there but blank, or not actually there at all? – Loren Rosen Apr 5 at 19:49
  • Yes it creates the file, but actually is blank. – William Apr 9 at 4:38
  • key question is where in the process does it fail? Can you see the image in another browser? at a greatly different screen or window size? after pulling down the image with ftp, curl, or wget? do all sizes of the image have the same problem (being mindful that with responsive images there's a whole set of images at different sizes)? If you re-upload the image does the problem re-occur? – Loren Rosen Apr 10 at 14:37
  • ... also, what if you try the 'regenerate' link you showed above? – Loren Rosen Apr 10 at 14:39
  • Actually the image of size 0 KB, you understand what I mean. – William Apr 11 at 11:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.