I'm trying to retrieve all children terms not as an array that get_term_children() function provides, rather as hierarchy level based like a tree structure.
I've been trying with
$childTerms = get_term_children( $term->term_taxonomy_id, $taxonomy);
if(!empty($childTerms)):
foreach($childTerms as $childTerm):
d(get_term($childTerm, $taxonomy)->name);
endforeach;
endif;
But, the problem is that I got all child terms of a parent term as of the same level. as follows:
string(2) "TV"
string(8) "Computer"
string(10) "Cell Phone"
string(6) "Camera"
string(27) "Security & Surveillance"
string(7) "Desktop"
string(6) "Laptop"
string(6) "Tablet"
Whereas, the desktop, laptop, tablet terms are children of parent computer term.
But, I would like to get them as follows:
string(2) "TV"
string(8) "Computer"
string(7) "Desktop"
string(6) "Laptop"
string(6) "Tablet"
string(10) "Cell Phone"
string(6) "Camera"
string(27) "Security & Surveillance"
how can I get this according to hierarchy level, like that of in WordPress menu?
First, you have to get all parent categories, and then based on parent id you can write a recurring function that gives you the child category of given id. check below code.
function get_child_categories( $parent_category_id ){
$html = '';
$child_categories = get_categories( array( 'parent' => $parent_category_id, 'hide_empty' => false, 'taxonomy' => $taxonomy ) );
if( !empty( $child_categories ) ){
$html .= '<ul>';
foreach ( $child_categories as $child_category ) {
$html .= '<li class="child">'.$child_category->name;
$html .= get_child_categories( $child_category->term_id );
$html .= '</li>';
}
$html .= '</ul>';
}
return $html;
}
function list_categories(){
$html = '';
$parent_categories = get_categories( array( 'parent' => 0, 'hide_empty' => false, 'taxonomy' => $taxonomy ) );
$html.= '<ul>';
foreach ( $parent_categories as $parent_category ) {
$html .= '<li class="parent">'.$parent_category->name;
$html .= get_child_categories( $parent_category->term_id );
$html .= '</li>';
}
$html.= '</ul>';
return $html;
}
add_shortcode( 'list_categories', 'list_categories' );
Output
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.