最新活动:买一送一!升级会员,最高返 500 抵扣券!>>>

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

WordPress wordpress从2.9版开始支持文章特色图像功能,使用wordpress的特色图像功能,会使用网站更加规范,提高页面加载速度,如何让主题支持特色图像功能很简单。 第一步,添加主题对特色图像功能的支持 将下面代码主题functions.php文件中: // 添加特色图像功能 add_theme_s...
为WordPress主题添加特色图像功能
WordPress

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

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

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

// 添加特色图像功能
add_theme_support('post-thumbnails');
set_post_thumbnail_size(130, 100, true); // 图片宽度与高度

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

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

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

<?php 
if (has_post_thumbnail()) {
     // 显示特色图像
     the_post_thumbnail();
} else {
     // 设置特色图像
     $attachments = get_posts(array(
          'post_type' => 'attachment',
          'post_mime_type'=>'image',
          'posts_per_page' => 0,
          'post_parent' => $post->ID,
          'order'=>'ASC'
     ));
     if ($attachments) {
          foreach ($attachments as $attachment) {
               set_post_thumbnail($post->ID, $attachment->ID);
               break;
          }
          // 显示特色图像
          the_post_thumbnail();
     }
} ?>

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

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

has_post_thumbnail()
set_post_thumbnail()
the_post_thumbnail()

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

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

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

// 特色图像
add_filter('the_content', 'set_featured_image_from_attachment');
function set_featured_image_from_attachment($content) {
     global $post;
     if (has_post_thumbnail()) {
          // 显示特色图像
          $content = the_post_thumbnail() . $content;
     } else {
          // 获取和设置特色图像 
          $attachments = get_children(array(
               'post_parent' => $post->ID,
               'post_status' => 'inherit',
               'post_type' => 'attachment',
               'post_mime_type' => 'image',
               'order' => 'ASC',
               'orderby' => 'menu_order'
          ));
          if ($attachments) {
               foreach ($attachments as $attachment) {
                    set_post_thumbnail($post->ID, $attachment->ID);
                    break;
               }
               // 显示特色图像
               $content = the_post_thumbnail() . $content;
          }
     }
     return $content;
}

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

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

给TA打赏
共{{data.count}}人
人已打赏
wordpress教程

WordPress 程序中xmlrpc.php是什么文件?删除有影响吗?

2023-2-16 23:48:33

wordpress教程

IE浏览器下,让免插件读者墙显示留言者名字

2023-2-16 23:48:36

!
你也想出现在这里?立即 联系我们吧!
信息
0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
搜索