为WordPress主题添加特色图像功能

featured image

wordpress从2.9版开始支持文章特色图像功能,使用wordpress的特色图像功能,会使用网站更加规范,提高页面加载速度,如何让主题支持特色图像功能很简单。

第一步,添加主题对特色图像功能的支持

将下面代码主题functions.php文件中:

  1. add_theme_support(\’post-thumbnails\’);
  2. set_post_thumbnail_size(130, 100, true); 

其中图片的长宽可以自行修改。

第二步,添加特色图像调用代码

将下面的代码添加到主题模板的适当位置,比如分类归档模板archive.php主循中:

  1. <?php 
  2.  (has_post_thumbnail()) {
  3.      
  4.      the_post_thumbnail();
  5.  {
  6.      
  7.       = get_posts((
  8.           \’post_type\’ => \’attachment\’,
  9.           \’post_mime_type\’=>\’image\’,
  10.           \’posts_per_page\’ => 0,
  11.           \’post_parent\’ => ->ID,
  12.           \’order\’=>\’ASC\’
  13.      ));
  14.       () {
  15.            (  ) {
  16.                set_post_thumbnail(->ID, ->ID);
  17.                ;
  18.           }
  19.           
  20.           the_post_thumbnail();
  21.      }
  22. } ?>

代码说明,如果未手动设置特色图像,那么会自动调用第一个图片附件的“缩略图”作为特色图像,并显示它。

注:代码中所使用的WP函数:

  • has_post_thumbnail()
  • set_post_thumbnail()
  • the_post_thumbnail()

可以到官方Codex查看详细使用说明,并根据需要加以修改。

调用显示特色图像还可以使用另一种方法:

如果你认为将特色图像调用代码加到主题模板主循环中看上去会很乱,可以将下面的代码添加到主题functions.php 文件中:

  1. add_filter(\’the_content\’, \’set_featured_image_from_attachment\’);
  2.  set_featured_image_from_attachment() {
  3.       ;
  4.       (has_post_thumbnail()) {
  5.           
  6.            = the_post_thumbnail() . ;
  7.      }  {
  8.           
  9.            = get_children((
  10.                \’post_parent\’ => ->ID,
  11.                \’post_status\’ => \’inherit\’,
  12.                \’post_type\’ => \’attachment\’,
  13.                \’post_mime_type\’ => \’image\’,
  14.                \’order\’ => \’ASC\’,
  15.                \’orderby\’ => \’menu_order\’
  16.           ));
  17.            () {
  18.                 (  ) {
  19.                     set_post_thumbnail(->ID, ->ID);
  20.                     ;
  21.                }
  22.                
  23.                 = the_post_thumbnail() . ;
  24.           }
  25.      }
  26.       ;
  27. }

这段代码基本原理与上面的相同 ,除了使用get_children过滤the_content(),而不是get_posts()。

原文:Set attachment as featured image

    © 版权声明
    THE END
    喜欢就支持一下吧
    点赞0 分享
    评论 抢沙发

    请登录后发表评论

      暂无评论内容