Import WordPress post images as featured image from external URL

I currently have a CSV file which has 2 columns – one for the Post ID and one for the image URL. There are 10,000 posts, and therefore 10,000 images.

I need to import these into WordPress and set each image as the Featured image.

Read More

How can this be achieved? I am aware there are plugins which will display the featured image from an external URL, but I actually need to import the images onto the same server (as the new website is being built on a different server, the domains DNS will be updated to go live – rendering the old full path URL’s useless).

Related posts

3 comments

  1. I would like to add to davemac’s answer to complete it.

    You would have to programmatically insert post with wp_insert_post() and save the post id that will be returned by the function.

    You would then run media_sideload_image() to download the image from the url to the wp site, save the returned value as a variable, which is html element of the image eg <img src="http:mywpsite/wp-content/....">.

    Strip the variable so youre only left with the src eg http:mywpsite/wp-content/.... and use this for attachment_url_to_postid() which will return the attachment id.

    With this, we have all the necessary components to meet our objective. Now use the post id and the attachment id to set the featured images using set_post_thumbnail()

    That’s it!

    The code would look a bit like

    $post_id = wp_insert_post($array);//create new post and save its id
    $img = media_sideload_image( $url, $post_id);//download image to wpsite from url
    $img = explode("'",$img)[1];// extract http.... from <img src'http...'>
    $attId = attachment_url_to_postid($img);//get id of downloaded image
    set_post_thumbnail( $post_id, $attId );//set the given image as featured image for the post
    
  2. @omer Farooq’ answer is helpful, but to extend on that and set the image as the featured image for the post (as OP asked for), you can do the following:

    // will return the attachment id of the sideloaded img
    $image_id = media_sideload_image( $image_url, $post_id, $filename, 'id' );
        
    // set as featured image
    set_post_thumbnail( $post_id, $image_id );
  3. WordPress already has a built-in function called media_sideload_image for exactly this kind of functionality. This function will download image and attach it to your post.

    So lets suppose you dump all the records from csv to an array, and it has 1000 indexes each with 2 items “post_id” and “image_url”. Now the image_url of the first item would be at $csv_items[0][‘image_url’]. Once you have this you can simply foreach the array and attach them to the relavant post ids.

    <?php 
    foreach($csv_items as $csv_item){
        $image = media_sideload_image($csv_item['image_url'], $csv_item['post_id']);
    }?>
    

Comments are closed.