我有自定义帖子类型的3个级别的类别,类别,子类别和子子类别.我试图使用cmb2在下拉列表中显示这些类别,我的代码只显示2个级别的类别和缺少第三级.
Category 1
-- child category 1
-- child category 2
-- addon category 1
-- addon category 2
-- child category 3
-- child category 4
-- addon category 1
-- addon category 2
Category 2
-- child category 1
-- child category 2
-- addon category 1
-- addon category 2
-- child category 3
-- child category 4
-- addon category 1
-- addon category 2
我正在使用cmb2在select2中使用multiselect选项获取这些类别.
并记下以下代码:
function gp_get_cmb_options_array_tax( $taxonomy, $args = array() ) {
if ( empty( $taxonomy ) ) { return; }
$defaults = array(
'hide_empty' => 0,
);
$args = wp_parse_args( $args, $defaults );
$terms = get_terms( $taxonomy, $args );
/**
* https://developer.wordpress.org/reference/functions/_get_term_hierarchy/
*/
$hierarchy = _get_term_hierarchy( $taxonomy );
$term_list = array();
foreach ( $terms as $term ) {
if( $term->parent ) {
continue;
}
$term_list[ $term->term_id ] = $term->name;
if( isset( $hierarchy[ $term->term_id ] ) ) {
foreach ( $hierarchy[ $term->term_id ] as $child ) {
$child = get_term( $child, $taxonomy );
$term_list[ $child->term_id ] = $term->name . ' > ' . $child->name;
}
}
}
return $term_list;
}
和下拉显示如下:
Category 1
Category 1 > child category 1
Category 1 > child category 2
Category 1 > child category 3
Category 1 > child category 4
Category 2
Category 2 > child category 1
Category 2 > child category 2
Category 2 > child category 3
Category 2 > child category 4
虽然应该表现得像
Category 1
Category 1 > child category 1
Category 1 > child category 2
Category 1 > child category 2 > addon category 1
Category 1 > child category 2 > addon category 2
Category 1 > child category 3
Category 1 > child category 4
最佳答案 你只需要更深层次地循环:
function gp_get_cmb_options_array_tax( $taxonomy, $args = array() ) {
if ( empty( $taxonomy ) ) { return; }
$defaults = array(
'hide_empty' => 0,
);
$args = wp_parse_args( $args, $defaults );
$terms = get_terms( $taxonomy, $args );
/**
* https://developer.wordpress.org/reference/functions/_get_term_hierarchy/
*/
$hierarchy = _get_term_hierarchy( $taxonomy );
$term_list = array();
foreach ( $terms as $term ) {
if( $term->parent ) {
continue;
}
$term_list[ $term->term_id ] = $term->name;
if( isset( $hierarchy[ $term->term_id ] ) ) {
foreach ( $hierarchy[ $term->term_id ] as $child ) {
$child = get_term( $child, $taxonomy );
$term_list[ $child->term_id ] = $term->name . ' > ' . $child->name;
if( !isset( $hierarchy[ $child->term_id ] ) )
continue;
foreach ($hierarchy[ $child->term_id ] as $subchild) {
$subchild = get_term( $subchild, $taxonomy );
$term_list[ $subchild->term_id ] = $term->name . ' > ' . $child->name. ' > ' .$subchild->name;
}
}
}
}
return $term_list;
}