I have a bunch of old posts on a blog that I would like to assign a featured image to.
I have retrieved all the images I would like to use for each post.
I saved each image file name after the slug of each post.
I would like to retrieve all posts, grab the slug name from each post, search the specified directory where the image files are uploaded, when the post slug matches the image file name, set that image as the featured image for that particular post, and iterate through all posts.
I am not sure how to go about doing this, but I have provided some example code I found, along with a few useful (hopefully) links.
The following code is used to retrieve all posts and update a particular post:
$allPosts = get_posts(array('numberposts' => -1, 'post_type' => 'post'));
foreach($allPosts as $thePost){
$my_post = array();
$my_post['post_type'] = $thePost->post_type;
$my_post['ID'] = $thePost->ID;
$my_post['post_name'] = autoSlug($thePost->post_title);
wp_update_post($my_post);
}
Note: I have a special function for generating post slugs based off the post_title. (I don’t use the WP default slug.)
Useful links:
Wrote a script myself, along with a blog post. Contributions for improvements are appreciated. Refer to this link for answer Set WordPress Featured Image For All Post Slugs Matching Image File Name in Specified Directory:
you save my life, your code just needs some adjustments and works like a charm. here it is.