WordPress教程

如何为WordPress网站文章添加特色图像

阿里云

WordPress 的特色图像是一个很实用的功能,可以在文章列表中为每篇文章添加一张缩略图。如果当前文章中没有图片,但又想显示一张默认的缩略图该怎么办?调用媒体库中某个图片作为默认的缩略图,将下面的代码添加到当前主题的 functions.php 中:

  1. function wpforce_featured() {
  2.     global $post;
  3.     $already_has_thumb = has_post_thumbnail($post->ID);
  4.     if (!$already_has_thumb)  {
  5.         $attached_image = get_children( "post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1" );
  6.         if ($attached_image) {
  7.             foreach ($attached_image as $attachment_id => $attachment) {
  8.                 set_post_thumbnail($post->ID, $attachment_id);
  9.             }
  10.         } else {
  11.             set_post_thumbnail($post->ID, '11');
  12.         }
  13.     }
  14. }  //end function
  15. add_action('the_post', 'wpforce_featured');
  16. add_action('save_post', 'wpforce_featured');
  17. add_action('draft_to_publish', 'wpforce_featured');
  18. add_action('new_to_publish', 'wpforce_featured');
  19. add_action('pending_to_publish', 'wpforce_featured');
  20. add_action('future_to_publish', 'wpforce_featured');
也想出现在这里?联系我们
创客主机

上面代码中的数字 11,是媒体库中某个图片附件的 ID 号。

如何为 WordPress 网站文章添加特色图像

已有 334 人购买
查看演示升级 VIP立刻购买

收藏
(1)

发表回复

热销模板

Ashade - 作品展示摄影相册WordPress汉化主题
LensNews

本站承接 WordPress / PbootCMS / DedeCMS 等
系统建站、仿站、开发、定制等业务!