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

WordPress:在自定义文章类型Papers的单页模板中显示当前Territorios分类法名称

嘿,我懂你的困扰——明明觉得应该很简单,但就是找不到顺手的解决方案对吧?别担心,在WordPress里给自定义文章类型Papers的单页显示所属的Territorios分类,其实几步就能搞定,我给你两个实用的方法:

方法1:显示所有所属的Territorios分类

如果你的Paper可能属于多个Territorios分类,用这个方法可以逐个输出它们的名称。在single-papers.php模板的合适位置(比如文章标题下方、内容区块旁)插入这段代码:

<?php
// 获取当前Paper文章所属的Territorios分类集合
$territorios_terms = get_the_terms(get_the_ID(), 'Territorios');

// 验证分类是否存在且无错误
if ($territorios_terms && !is_wp_error($territorios_terms)) {
    // 遍历每个分类并输出名称
    foreach ($territorios_terms as $term) {
        // 用esc_html()转义输出,避免安全风险,这是WordPress开发的最佳实践
        echo '<span class="territorio-label">' . esc_html($term->name) . '</span>';
    }
}
?>
方法2:只显示第一个所属分类

如果你的每篇Paper只会对应一个Territorios分类,那可以简化代码,直接取出第一个分类项:

<?php
$territorios_terms = get_the_terms(get_the_ID(), 'Territorios');
if ($territorios_terms && !is_wp_error($territorios_terms)) {
    // 取出数组中的第一个分类
    $primary_territorio = reset($territorios_terms);
    // 可以自定义输出的文本和样式,比如加上标签说明
    echo '<p>所属区域:<strong>' . esc_html($primary_territorio->name) . '</strong></p>';
}
?>

小提醒:

  • 确保你传入get_the_terms()的第二个参数'Territorios'和你注册自定义分类法时的分类法slug完全一致(大小写敏感哦)
  • 记得用esc_html()包裹输出内容,这能有效防止XSS攻击,是WordPress开发的标准操作

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 06:49:29