I'm trying to insert a post image thumbnail from my php scritp. It's inserting the post, the content, a download link, and I only need to set the thumbnail image to finish my script. This is my code but I can't figure out why is not working, anyhelp would be appreciated:

    $url = "http://www.test.com/wp-content/uploads/2015/12/".$title[$key1].".png";

$attr = array(
'src'   => basename($url),
'class' => "alignleft",
'alt'   => '',
'title' => trim( strip_tags( 'Logo' ) )
the_post_thumbnail('thumbnail', $attr );

You'll want to take a look at wp_insert_attachment and wp_generate_attachment_metadata.

You can't insert a featured image/thumbnail using the_post_thumbnail - that function only gets the thumbnail for the current post.

See: http://codex.wordpress.org/Function_Reference/wp_insert_attachment and http://codex.wordpress.org/Function_Reference/wp_generate_attachment_metadata


To set a thumbnail for a post you should upload the file to your server. Use the below function to upload the file from URL:

function upload_file($image_url, $post_id)
    $image = $image_url;

    $get = wp_remote_get($image);

    $type = wp_remote_retrieve_header($get, 'content-type');

    if (!$type) {
        return false;

    $mirror = wp_upload_bits(basename($image), '', wp_remote_retrieve_body($get));

    $attachment = array(
        'post_title' => basename($image),
        'post_mime_type' => $type

    $attach_id = wp_insert_attachment($attachment, $mirror['file'], $post_id);

    require_once(ABSPATH . 'wp-admin/includes/image.php');

    $attach_data = wp_generate_attachment_metadata($attach_id, $mirror['file']);

    wp_update_attachment_metadata($attach_id, $attach_data);

    return $attach_id;

Then run the function:

$url = 'http://yoursite.com/photo.jpg';
$post_id = 56;

upload_file($url, $post_id);

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.