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

如何让WordPress自定义分类法子术语始终显示在父术语前?

强制自定义分类法子术语优先显示的解决方案

要让country_category分类法的子术语始终显示在父术语前面,不要依赖get_the_term_list的默认输出(它的顺序由术语存储逻辑决定),可以手动获取并筛选术语,按需求拼接输出。

基础方案(单父单子女)

如果每篇文章只关联一个父术语和一个子术语,用以下代码替代原有的get_the_term_list:

<?php
$terms = get_the_terms( get_the_ID(), 'country_category' );
if ( $terms && ! is_wp_error( $terms ) ) {
    $parent = '';
    $child = '';
    foreach ( $terms as $term ) {
        // 父术语的parent属性为0
        if ( $term->parent === 0 ) {
            $parent = $term->name;
        } else {
            $child = $term->name;
        }
    }
    // 按子在前、父在后的格式输出,同时做容错处理
    if ( $child && $parent ) {
        echo '<p>' . esc_html( $child . ', ' . $parent ) . '</p>';
    } elseif ( $child ) {
        echo '<p>' . esc_html( $child ) . '</p>';
    } elseif ( $parent ) {
        echo '<p>' . esc_html( $parent ) . '</p>';
    }
}
?>

扩展方案(单父多子女)

如果一篇文章关联一个父术语和多个子术语(比如同一个国家下的多个州),用以下代码批量输出:

<?php
$terms = get_the_terms( get_the_ID(), 'country_category' );
if ( $terms && ! is_wp_error( $terms ) ) {
    $parent = '';
    $children = [];
    foreach ( $terms as $term ) {
        if ( $term->parent === 0 ) {
            $parent = $term->name;
        } else {
            $children[] = $term->name;
        }
    }
    // 遍历子术语,逐个拼接父术语输出
    if ( $children && $parent ) {
        foreach ( $children as $child ) {
            echo '<p>' . esc_html( $child . ', ' . $parent ) . '</p>';
        }
    } elseif ( $children ) {
        foreach ( $children as $child ) {
            echo '<p>' . esc_html( $child ) . '</p>';
        }
    } elseif ( $parent ) {
        echo '<p>' . esc_html( $parent ) . '</p>';
    }
}
?>

代码说明

  • 用get_the_terms获取当前文章的所有关联术语,相比get_the_term_list更灵活,能完全控制输出顺序
  • 通过术语的parent属性区分层级:parent=0是父术语,否则为子术语
  • 加入容错处理,避免只有父术语或只有子术语时出现错误输出

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 20:30:46