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.
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).
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
@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:
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.