WordPress自动为文章设置特色图像

WordPress特色图像实际就是文章缩略图,主要用于主题前台展示用。现在已经越来越多的主题做的功能强大而美观了,要美观就得有图显示才行,特色图像就起到这个作用。但是,默认下WordPress文章发布需为每篇文章手动设置一个特色图像,是不是觉得很麻烦呢?懒人手法就得自动为文章设置特色图像,节省一些时间。

今天介绍的自动为WordPress文章设置特色图像方法的原理是自动提取文章内第一张图片作为特色图像。这个方法还有个优点,如果你手动选择设置了特色图像,就可以覆盖这段代码功能,即使用你手动设置的特色图像。具体方法是将以下代码插入你的function.php文件中:

自动为WordPress文章设置特色图像代码

/*
自动为文章设置特色图像
*/
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);
                                }
                           }
                        }
      }  //end function
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');

WordPress自动为文章设置特色图像就这么简单,现在你就可以化繁为简,可以不用再手动设置特色图像了!


评论

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注