April 18, 2024

WordPress Autoset Featured Thumbnail Image

wp autoset featured image and thumbnail code

WordPress Autoset Featured Thumbnail Image : By adding a code snippet, you can autoset the first image as the featured image and thumbnail of the post without needing a plugin.

If you want to auto set the first image uploaded into the post as the featured image and thumbnail of the post, add this code snippets to your functions.php file.

Add the code below to the bottom line of the functions.php :

// Auto add featured image
function wpsites_auto_set_featured_image() {
   global $post;
   $featured_image_exists = has_post_thumbnail($post->ID);
      if (!$featured_image_exists)  {
         $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', 'wpsites_auto_set_featured_image');

If you have any question about this code and autosetting featured and thumbnail image on wordpress blogs, comment your problem below.

Leave a Reply

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


Notice: ob_end_flush(): failed to send buffer of zlib output compression (0) in /home/zussnet/niok.net/wp-includes/functions.php on line 5420