WordPress如何自动设置特色图片(封面图)?| How to automatically set your featured image on WordPress?

原文:https://xomisse.com/blog/auto-featured-image/

 

If you’ve recently changed your theme, you may be wondering why some post thumbnails aren’t being displayed anymore. This could be that the featured images aren’t set, but instead of manually editing each post individually to add a featured image there are ways to automatically set it.

You can use a plugin to do this or add a snippet of code to your theme files. If you feel confident doing this without a plugin, I’d recommend the coding method. But for those of you who would prefer to use a plugin, I’ve tried and tested three options for you.

How to automatically set the first image in your blog post as the featured thumbnail image on WordPress (with and without a plugin)

Set featured image using a plugin

Media Tools by Chris Olbekson
This plugin hasn’t been updated in five years so install with caution. I used it recently and it worked. Though if you have a lot of blog posts, you may need to do it in batches by selecting a date range and ensuring the progress bar reaches 100% before timing out. Deactivate and delete once you’re finished.

XO Featured Image Tools by Xakuro System
Upon activation go to Settings > XO Featured Image and choose from the options. Then go to Tools > Featured Image Tools and click the Generate Featured Images button. Deactivate and delete once you’re finished.

Get First Image Set As Featured Image by Venugopal
This plugin hasn’t been updated in over a year, however it did work for me on a test site. You activate the plugin and it automatically sets the featured image for all posts without one. Deactivate and delete once you’re finished.

Set the first post image as featured image on WordPress using code

As shown in my previous post, connect to your site via FTP.

Open your theme’s functions.php file and add this snippet from WPsites to it.

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

Refresh your site and you should see the featured thumbnails have now been added. You can remove this code once you’re done.

标签TAGS

与标签相关的文章

最新文章

热门文章

其他文章