Answer a question

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

Answers

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
Logo

更多推荐