wordpressbulkupdate

How to Find the first image in post content and add it to Featured Image


I have about 1000 posts on my wordpress website, but these posts do not have featured images. But instead, in all these posts there is one photo (the first photo in the article) that can be used as an index photo. How to find the first photo of the article in bulk and replace the featured photo. (The first photo in the article can be deleted)

I would appreciate if u helped me with this.

I tried to manually replace these photos, but there are too many posts. I read some articles in different forums about the possibility of using Python to do this.


Solution

  • Quite old post, but I'm facing the same problem, so I figured I'd provide what I found.

    First solution (paid)

    There is an existing WordPress plugin called Quick Featured Images whose pro version offers what you need (at least I figured reading their presentation, I did not test it myself).

    The base plan was a bit under 80$ with taxes last time I checked.

    Second solution (free)

    If you want something less easy but free, I found an article and a support ticket on a WordPress theme that mentioned the following bit of code :

    function auto_featured_image() {
        global $post;
     
        if (!has_post_thumbnail($post->ID)) {
            $attached_image = get_children( "post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1" );
             
          if ($attached_image) {
                  foreach ($attached_image as $attachment_id => $attachment) {
                       set_post_thumbnail($post->ID, $attachment_id);
                  }
             }
        }
    }
    // Use it temporary to generate all featured images
    add_action('the_post', 'auto_featured_image');
    // Used for new posts
    add_action('save_post', 'auto_featured_image');
    add_action('draft_to_publish', 'auto_featured_image');
    add_action('new_to_publish', 'auto_featured_image');
    add_action('pending_to_publish', 'auto_featured_image');
    add_action('future_to_publish', 'auto_featured_image');
    

    I did not find any free plugin that already does this, so I plan on creating a really simple one that implements this code and works with the last version of WordPress, nothing complicated.

    If I find the time to do it I'll update my answer with a link to the plugin I created.

    EDIT : I found this other StackOverflow post that also use the code I mentioned, but it does not seem to work for everything. Will look into the answer that was provided too.