Monday 4 November 2013

Automatically Set The Featured Image In WordPress

Important: All scripts hosted on widcraft.googlecode.com don't work anymore because Google has blocked that SVN repository.
Almost every WordPress theme developer is using WordPress' featured post image option in their latest themes, and it's a very great option. You can pick any image for your article before publishing

But ofter we forget to pick a featured image for out posts. Also there's no way to pick a featured image in WordPress' smartphone application. So today we're going to automatically set the featured image.

This snippet will automatically set the first image of your post as the featured image of the post. Note, you can always go and set another image as the featured image if you want to.

Add following snippet to your functions.php file:

function wpforce_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);
                                }
                           } else {
                                set_post_thumbnail($post->ID, '414');
                           }
                        }
      }  //end function
add_action('the_post', 'wpforce_featured');
add_action('save_post', 'wpforce_featured');
add_action('draft_to_publish', 'wpforce_featured');
add_action('new_to_publish', 'wpforce_featured');
add_action('pending_to_publish', 'wpforce_featured');
add_action('future_to_publish', 'wpforce_featured');

There is one more cool option in this code. If you don't have an image in the post, the above code will let you set a default featured image as well. You must edit the attachment ID according to your WordPress site. The example above uses the attachment ID "414"

Credits: WPForce
Important: Check our new website TricksPanda.com for WordPress tutorials, plugins and more.
 
Powered by Blogger.