如何在 WordPress 中获取自定义分类法的所有 parents/children 类别
How to get all parents/children categories of a custom taxonomy in WordPress
我正在开发自定义 WordPress 主题,我想显示所有分类列表
所以,例如,如果我想要这个结构:
父类别 1
- 儿童类别 1
- 儿童类别 2
- 儿童类别 3
1.1 - Grand Child Category 1
父类别 2
- 第 4 类儿童
- 第 5 类儿童
2.1. - Grand Child Category 2
你们能帮我解决这个难题吗
要创建此结构,也许使用辅助数组是解决方案。这不是一个 100% 的解决方案,它只会让你开始,你可以从这里开始,因为单独解决它会更有帮助。
$all_terms = array();
$taxonomy = 'category';
$parent_args = [
'taxonomy' => $taxonomy,
'parent' => 0,
'hide_empty' => false
];
$parent_terms = get_terms( $parent_args );
foreach ( $parent_terms as $parent_term ) {
$all_terms[ $parent_term->term_id ] = get_all_term_children( $parent_term, $taxonomy );
}
function get_all_term_children( $term, $taxonomy ){
if ( is_wp_error( get_term_children( $term->term_id, $taxonomy ) ) ) {
return;
}
return get_term_children( $term->term_id, $taxonomy );
}
试试这个功能:用你的分类替换 "taxonomy_name"。
wp_list_categories( array('taxonomy' => 'taxonomy_name', 'title_li' => "") );
输出:
注意:我用过WP 4.9.8
我正在开发自定义 WordPress 主题,我想显示所有分类列表
所以,例如,如果我想要这个结构:
父类别 1
- 儿童类别 1
- 儿童类别 2
- 儿童类别 3
1.1 - Grand Child Category 1
父类别 2
- 第 4 类儿童
- 第 5 类儿童
2.1. - Grand Child Category 2
你们能帮我解决这个难题吗
要创建此结构,也许使用辅助数组是解决方案。这不是一个 100% 的解决方案,它只会让你开始,你可以从这里开始,因为单独解决它会更有帮助。
$all_terms = array();
$taxonomy = 'category';
$parent_args = [
'taxonomy' => $taxonomy,
'parent' => 0,
'hide_empty' => false
];
$parent_terms = get_terms( $parent_args );
foreach ( $parent_terms as $parent_term ) {
$all_terms[ $parent_term->term_id ] = get_all_term_children( $parent_term, $taxonomy );
}
function get_all_term_children( $term, $taxonomy ){
if ( is_wp_error( get_term_children( $term->term_id, $taxonomy ) ) ) {
return;
}
return get_term_children( $term->term_id, $taxonomy );
}
试试这个功能:用你的分类替换 "taxonomy_name"。
wp_list_categories( array('taxonomy' => 'taxonomy_name', 'title_li' => "") );
输出:
注意:我用过WP 4.9.8