Programmatically Set First Image as Featured

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+

Leave a Comment