If you are one of the WordPress users, you might know about the featured image in the Write post panel. Today I will tell you how to set a featured image automaitcally in your blog post. Some people find this task quite boring and time consuming to a speacial featured image to there blog post and then to include it in the post as well. So by the bit of code below you will not be worrying a lot now :)

Add the Featured Image Automatically in WordPress

In you theme's funtions.php file go at the end and add the below code before ?>

 

/*Add the Featured Image Automatically in WordPress*/
function autoimg_featured() {
          global $post;
          $already_has_thumb = has_post_thumbnail($post->ID);
              if (!$already_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', 'autoimg_featured');
add_action('save_post', 'autoimg_featured');
add_action('draft_to_publish', 'autoimg_featured');
add_action('new_to_publish', 'autoimg_featured');
add_action('pending_to_publish', 'autoimg_featured');
add_action('future_to_publish', 'autoimg_featured');

What this function will do?

This function will check if you have set a custom image as a featured image, it keep it as it is. Otherwise if there is no featured image found, it add the first image from the post as the featured Image.

Your Turn:

  • Was that useful?
  • Tell us how much time it saved for you !