您现在的位置是:首页 > 网站制作 > WordpressWordpress

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

杰帅2023-08-19【Wordpress】人已围观

简介WordPress的特色图像是一个很实用的功能,为每篇文章增加一个特色图像,可以使blog各个部分都更生动。比如首页每篇文章都有自己的缩略图,相关文章中用缩略图告诉用户这些文章的主题,或者在侧栏加一个特色文章功能,显示文章特色图像。

WordPress的特色图像是一个很实用的功能,为每篇文章增加一个特色图像,可以使blog各个部分都更生动。比如首页每篇文章都有自己的缩略图,相关文章中用缩略图告诉用户这些文章的主题,或者在侧栏加一个特色文章功能,显示文章特色图像。

特色图像需要用户手动选择,有些不方便,不是每次都能想起来点一下设置特色图像按钮,如果能自动为WordPress文章添加特色图像,就方便多了。

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

这里有一段很实用的代码,可以自动将文章中的第一张图片设置为特色图像,如果你手动设置了特色图像,可以覆盖这段代码。将下面的代码丢到当前主题的functions.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);
                                }
                           }
                        }
      }  //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');

代码来自:Automatically Set the Featured Image in WordPress

Tags:functions   wordpress教程   特色图像

很赞哦! ()

文章评论

本站推荐

站点信息

  • 建站时间:2018-10-24
  • 网站程序:帝国CMS7.5
  • 主题模板《今夕何夕》
  • 文章统计1172篇文章
  • 标签管理标签云
  • 统计数据百度统计
  • 微信公众号:扫描二维码,关注我们