Reset all posts featured images

Messed up featured images? Here is a code snippet to update every WordPress featured image in your posts.

Recently I changed some code that had an empty value in the post ID. That made the function unable to set a featured image in the current post. What ended up happening was the most recent image got set as the featured post for EVERY POST, on EVERY update. Oops.

Here is a snippet to fix the problem:

Not sure what happened to the code…

Austin
Austin

πŸ’πŸ½β€β™‚οΈ Husband to Jeana.
⚾️ Dodgers & Brewers.
πŸ’» PHP Engineer.
πŸŒπŸΌβ€β™‚οΈGolfer; ~13 HDC.
🌱 Hydroponic Gardner.
🍿 Plex nerd.
πŸš™ '15 WRX, '22 Model 3 LR, & '66 Corvette C2.

Follow me on Twitter @TheFrosty & Instagram @TheFrosty.

Articles: 293

5 Comments

  1. Oh, I had a very similar issue a few months ago. This would do the same trick, very quick:

    DELETE FROM wp_postmeta
    WHERE  meta_key = '_thumbnail_id';
    
    INSERT INTO wp_postmeta
                (post_id,
                 meta_key,
                 meta_value)
    SELECT post_parent,
           '_thumbnail_id',
           Min(ID)
    FROM   wp_posts
    WHERE  post_type = 'attachment'
       AND post_mime_type LIKE '%image%'
       AND post_parent > 0
       AND post_parent NOT IN (SELECT post_id
                               FROM   wp_postmeta
                               WHERE  meta_key = '_thumbnail_id')
    GROUP  BY post_parent;
    
  2. Oh, I had a very similar issue a few months ago. This would do the same trick, very quick:

    DELETE FROM wp_postmeta
    WHERE  meta_key = '_thumbnail_id';
    
    INSERT INTO wp_postmeta
                (post_id,
                 meta_key,
                 meta_value)
    SELECT post_parent,
           '_thumbnail_id',
           Min(ID)
    FROM   wp_posts
    WHERE  post_type = 'attachment'
       AND post_mime_type LIKE '%image%'
       AND post_parent > 0
    GROUP  BY post_parent;
    

    and adding:

    AND post_parent NOT IN (SELECT post_id
                               FROM   wp_postmeta
                               WHERE  meta_key = '_thumbnail_id')
    

    to the last SELECT will do this only if the post doesn’t have a featured image already.

  3. I just transferred my blog and have an problem. My images are not showing up in the posts and my featured image is not showing up. I have tried fixes,plugins is there a code I can use or a plugin that will fix the problem. Thanks

Comments are closed.