Quantcast
Channel: WordPress
Viewing all articles
Browse latest Browse all 77

WordPress Quick Tip #4 - Automatically Set the First Post Image as a Featured Image

$
0
0
WordPress Quick Tip #4 - Automatically Set the First Post Image as a Featured Image

Have you ever run into the situation where you have a lot of posts without a featured image and you need to change that to be able to use WordPress Themes which depend upon featured images in their layout? We’ve got a simple solution to this problem.

Use the simple script listed below. We recommend placing it in the theme's functions.php file:

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');

This script is very simple - it checks if the specific post has a featured image set and, if the featured image isn't set, the script checks for the first attached image and sets it as a featured image. This operation is executed for every save or post operation.

As this instruction is executed on every post displayed, introducing a slight performance hit to your website, we recommend removing the following lines once all the featured images have been generated:

// Use it temporary to generate all featured images
add_action('the_post', 'auto_featured_image');

Here are two important details to take away from this:

  1. The featured image must be removed from the media manager.
  2. The attached image must first be used in the specific article; if the image was used and attached to a different post, it will not be set as a featured image for the other post.

It is for this reason I recommend only using this method to migrate your older posts in the old format, and once done setting the featured image feature manually.


Viewing all articles
Browse latest Browse all 77

Trending Articles