You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WordPress文章中仅显示第二个标签

如何让WordPress仅显示文章的第二个标签?

原代码会循环输出文章的所有标签,现在需要修改为仅显示第二个标签(假设每篇文章固定分配两个标签),以下是修改后的代码:

<h3 class="entry-title">                
    <a href="<?php echo esc_url(get_permalink()); ?>" title="<?php echo esc_attr(get_the_title()); ?>">
        <?php 
        $posttags = get_the_tags(); 
        // 确保存在标签且至少有2个标签,避免报错
        if ($posttags && count($posttags) >= 2) {
            echo '<ul class="myitems">';
            // 直接取第二个标签(PHP数组索引从0开始,第二个对应索引1)
            echo '<li>' . $posttags[1]->name . '</li>';
            echo '</ul>'; 
        } 
        ?>          
    </a>            
</h3>

修改说明:

  • 移除原代码的foreach循环,直接通过数组索引$posttags[1]获取第二个标签(第一个标签对应索引0)
  • 新增count($posttags) >= 2的判断逻辑,防止文章标签数量不足2个时出现PHP错误
  • 保留原有的HTML结构和WordPress安全函数(esc_url、esc_attr),保障代码安全性

内容的提问来源于stack exchange,提问作者John

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 05:54:22