Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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:

  1. get_posts
  2. wp_update_post
  3. Post_Thumbnails
  4. wp_upload_dir
  5. wp_insert_attachment
share|improve this question

1 Answer 1

up vote 1 down vote accepted

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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