I have 3 levels of categories, categories, subcategories, and subcategories for a custom post type. I am trying to show these categories in a dropdown using cmb2 , my code shows only 2 levels of categories and there is no third level.
Category 1
Category 2
and I use cmb2 to get these categories in select2 using the multiselect option.
and write down the following code:
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 );
$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;
}

and the dropdown menu is shown as:
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
Although it should look like
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
source
share