如何让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
相关产品推荐
相关产品推荐

