6

I have over 400 posts with images inside them, I have got a new template which requires a featured image for each post, something my last template did not require... I am wondering if there is a script I can add to my functions.php to be able to grab the first image in each post and set it as the featured... So far i have found this, but it is not working...

function auto_set_featured() {
global $post;
$has_thumb = has_post_thumbnail($post->ID);
if (!$has_thumb)  {
$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);
        }
    }
}
}
add_action('the_post', 'auto_set_featured');
add_action('save_post', 'auto_set_featured');
add_action('draft_to_publish', 'auto_set_featured');
add_action('new_to_publish', 'auto_set_featured');
add_action('pending_to_publish', 'auto_set_featured');
add_action('future_to_publish', 'auto_set_featured');

This script will work for new posts, but i need it to affect all my older posts, any suggestions?

  • i use this plugin and it works very fine.. the name of the plusin is Get first image as featured image – mr daniel May 31 '18 at 8:32
3

Regarding the code you posted, I would say some things:

  • you can avoid using 6 different actions because one is enough: 'save_post' is triggered everytime a post is created or updated
  • you can drop globalize $post: 'save_post' will pass the post id, you can use it, in addition, preparing the function to receive an argument will help you to run the same function programmatically

The edited version of your code becomes:

function auto_set_featured( $post = NULL ) {
  // retrieve post object
  $post = get_post( $post ); 
  // nothing to do if no post, or post already has thumbnail
  if ( ! $post instanceof WP_Post || has_post_thumbnail( $post->ID ) )
     return;
  // prepare $thumbnail var
  $thumbnail = NULL;
  // retrieve all the images uploaded to the post
  $images    = get_posts( array(
    'post_parent'    => $post->ID,
    'post_type'      => 'attachment',
    'post_status'    => 'inherit',
    'post_mime_type' => 'image',
    'posts_per_page' => 1
  ) );
  // if we got some images, save the first in $thumbnail var
  if ( is_array( $images ) && ! empty( $images ) )
     $thumbnail = reset( $images );
  // if $thumbnail var is valid, set as featured for the post
  if ( $thumbnail instanceof WP_Post )
     set_post_thumbnail( $post->ID, $thumbnail->ID );
}

add_action( 'save_post', 'auto_set_featured' );

Now, the only thing you need for old posts, is to retrieve them with a query and then run the same function for every post.

Just keep attention to perform the task only once: it's a very time & resource consuming task, so it should be ran only once, possibly on backend.

I'll use a transient for the purpose:

add_action( 'admin_init', function() {

  if ( (int) get_transient(' bulk_auto_set_featured' ) > 0 )
     return;

  $posts = get_posts( 'posts_per_page=-1' ) ;
  if ( empty( $posts ) )
    return;

  array_walk( $posts, 'auto_set_featured' );

  set_transient( 'bulk_auto_set_featured', 1 );
});

After adding this code to your functions.php or to a plugin, log in the backend, and prepare yourself to wait some seconds before the dashboard appear, but after that all post should have a thumbnail, at least every post that has an image uploaded in it.

If everything goes as it should you can the remove the last code snippet keeping only the first.

Note my code require php 5.3+

  • This gave me: Notice: Undefined offset: 0 in /nas/content/live/site/wp-content/themes/yeast/functions.php on line 1166 Notice: Trying to get property of non-object in /nas/content/live/site/wp-content/themes/yeast/functions.php on line 1166 – Nathan Dec 9 '15 at 2:49
  • @Nathan I imporved code and add some comments, to make more clear what code does. – gmazzap Dec 9 '15 at 12:26
2

Use this code in your child themes functions file and them regenerate thumbnails

function wpsites_auto_set_featured_image() {
      global $post;
      $featured_image_exists = has_post_thumbnail($post->ID);
          if (!$featured_image_exists)  {
          $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);
                            }
                       }
                    }
  }
add_action('the_post', 'wpsites_auto_set_featured_image');
0

"Set All First Images As Featured" worked for me.

With a hack it could reverse the operation.

Easy Add Thumbnail may also do the trick, and the pro version of Quick Featured Images does it, and I think I saw another plugin that does this when I searched.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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