Plugins WordPress

Add the Featured Image Automatically in WordPress

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 !

By Freakify Editorial

The post was written by the Freakify Editorial Team. used to be managed by Awais, Maedah and their team before its acquisition.

20 replies on “Add the Featured Image Automatically in WordPress”

Thanks for the Post Ahmad Bro, but I think you should write lengthy posts, not so short posts! and Also should tell simple ways not such codes! they always confuse me and are the headache.!

Very nice and informative post, I love it but don’t know if I should do it on my theme (genesis framework) since they warn that one shouldn’t touch the framework except the child theme so as not to miss updates when available.

Hi! I used your code to add the featured images automatically but it doesn’t work… I’m using a RSS feed to add posts to my site and maybe that’s the problem. Do you know how to make it work?

Thanks in advance and btw Great site! =)

I love this and am in desperate need of something like this, BUT I am so scared to touch the code at all, I wish I was braver, I love your site, you share very useful information!!
I am still new to Word Press and your site has helped me so much already, Thank you!

Comments are closed.