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

WordPress技术问询:如何用分类法术语替代分类进行显示

解决自定义分类法术语显示问题

别担心,我来帮你搞定这个需求!你之前的代码是针对WordPress默认的category分类法,要替换成自定义分类法的术语,我们只需要把get_the_category()换成专门针对自定义分类法的函数就行,不用太纠结get_term,直接用get_the_terms更方便。

核心修改思路

原来的get_the_category()只能获取默认分类,而自定义分类法需要用get_the_terms()函数,它能指定你要获取的分类法slug,然后返回对应的术语列表。

替换后的代码示例

把下面的代码替换你原来的代码,记得把your_custom_taxonomy改成你实际的自定义分类法slug(比如你创建的分类法叫product_tag,就填这个):

<?php
// 替换为你的自定义分类法slug
$custom_taxonomy = 'your_custom_taxonomy';
// 获取当前文章的自定义分类法术语
$terms = get_the_terms(get_the_ID(), $custom_taxonomy);

// 检查是否获取到有效术语,同时避免错误
if ($terms && !is_wp_error($terms)) {
    // 显示第一个术语(和你原来的逻辑一致)
    $first_term = $terms[0];
    echo '<a href="' . get_term_link($first_term, $custom_taxonomy) . '" title="' . esc_attr($first_term->name) . '">' . esc_html($first_term->name) . '</a>';
    
    // 如果有多个术语,显示省略号
    if (count($terms) > 1) {
        echo ' ...';
    }
}
?>

关键细节说明

  1. 找到自定义分类法slug:如果你不确定slug是什么,去WordPress后台,打开你的自定义分类法页面(比如“产品分类”),看浏览器地址栏里的taxonomy=后面的字符串,那就是slug。
  2. 安全处理:代码里用了esc_attr()和esc_html(),是为了防止恶意代码注入,这是WordPress开发的好习惯,建议保留。
  3. 错误处理:!is_wp_error($terms)是为了避免分类法不存在时出现报错,让代码更健壮。

扩展:显示所有术语(可选)

如果你不想只显示第一个加省略号,而是要列出所有术语,可以用下面的代码:

<?php
$custom_taxonomy = 'your_custom_taxonomy';
$terms = get_the_terms(get_the_ID(), $custom_taxonomy);

if ($terms && !is_wp_error($terms)) {
    $term_links = [];
    foreach ($terms as $term) {
        $term_links[] = '<a href="' . get_term_link($term, $custom_taxonomy) . '" title="' . esc_attr($term->name) . '">' . esc_html($term->name) . '</a>';
    }
    // 用逗号分隔所有术语
    echo implode(', ', $term_links);
}
?>

这样就能完美替换原来的默认分类显示,改成自定义分类法的术语啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:16:33