WordPress

Automatically Set Post Featured Image

A post featured image was introduced in WordPress version 2.9, it is a thumbnail that can be set to the post as a featured image of your post. It will not be displayed on the page but it's up to the WordPress theme to decide when to display it.

Enable Theme Support For Featured Post

By default themes do not support this feature you need to add some code to the functiona.php file.

add_theme_support( 'post-thumbnails' );

Set Featured Image

There is a meta box on the post screen where you can set an image to be the featured image on the post.

featured_post

Automatically Set Featured Image

But if you forget to place a featured image on your post then your theme won't be able to display an image. Here is a snippet which will automatically set the first image from the post to be your featured image.

<?php
function autoset_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', 'autoset_featured');
add_action('save_post', 'autoset_featured');
add_action('draft_to_publish', 'autoset_featured');
add_action('new_to_publish', 'autoset_featured');
add_action('pending_to_publish', 'autoset_featured');
add_action('future_to_publish', 'autoset_featured');
?>

Change The Set Featured Image Text

To change the text in the set featured image meta box you can use the WordPress filter admin_post_thumbnail_html and replace the content with the new text.

function change_featured_image_text( $content ) {
    return $content = str_replace( __( 'Set featured image' ), __( 'Set post thumbnail image' ), $content);
}
add_filter( 'admin_post_thumbnail_html', 'change_featured_image_text' );
Back to top ^

Join Paulund

  • Get access to 100s of premium tutorials and downloadable content
  • Members content consists of Premium WordPress plugins, CSS packages, jQuery packages, tutorial demo files and templates for 100s of web development tutorials
  • In-depth development tutorials
  • Priority tutorial requests
  • Priority email development support
  • No ads

Here at Paulund you'll find Web Development tutorials and snippets focusing mainly on PHP, WordPress and CSS. Members will get access to premium tutorials that go into more detail about development with these languages. You will also get access to downloadable premium content based on the tutorial.

Join Paulund

Leave a Reply

Your email address will not be published. Required fields are marked *