everyone! I've been making a wordpress plugin which gets seperate instagram photos and then puts them in shortcodes. Though, the shortcodes display images not saved in WP images folder, but directly from instagram. It makes the server loading times drastically increase.

So I searched WP dev forums and found this function which sets the featured image for the specified post.

function Generate_Featured_Image( $image_url, $post_id  ){
    $upload_dir = wp_upload_dir();
    $image_data = file_get_contents($image_url);
    $filename = 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, $post_id );
    require_once(ABSPATH . 'wp-admin/includes/image.php');
    $attach_data = wp_generate_attachment_metadata( $attach_id, $file );
    $res1= wp_update_attachment_metadata( $attach_id, $attach_data );
    $res2= set_post_thumbnail( $post_id, $attach_id );

What am I missing is the fact that the photos I take get updated shortly and the featured image doesn't change after that. Would there be any way to update the featured image as soon as a new instagram photo gets uploaded? Or just every hour or so. Thanks a bunch, guys!

  • The way you're downloading and saving the data to the media library is rather fragile and longwinded, is there a specific reason you didn't use media_sideload_iamge( $url, $post_id ); ?
    – Tom J Nowell
    Sep 24, 2017 at 2:29
  • @TomJNowell Thanks for the reference to media_sideload_image`function. Sep 24, 2017 at 3:01

1 Answer 1


Once you get URL of the image from Instagram and you know id of the post, you can use use the function from your question. You have to modify the code for the only if statement in it:

if( wp_mkdir_p( $upload_dir[ 'path' ] ) ) {
    $file = $upload_dir[ 'path' ] . '/' . $filename;
} else {
    $file = $upload_dir[ 'basedir' ] . '/' . $filename;

This function will upload the image to the media library and set it as a featured image for your post. Tested!

Or, based on suggestion by @TomJNowell from his comment, use this code:

$attach_id = media_sideload_image( $image_url, $post_id, 'Instagram image', 'id' );
set_post_thumbnail( $post_id, $attach_id );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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