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

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

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

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

UpChecker

Reliable uptime monitoring and instant alerts for any website downtime.

  • Uptime Monitoring
  • Performance Monitoring
  • SSL Certificate Alerts
  • Domain Monitoring
  • DNS Checker
  • XML Sitemap Monitoring