2

I need to order parent terms by their children count:

function sort_terms_by_children_count ( $terms ) {
    $sort_terms_by_children_count = array();
    foreach($terms as $term) {
        $count = count (get_terms( $terms, array( 'child_of' => $term->term_id, 'hide_empty' => false, ) ));
        $sort_terms_by_children_count[$count] = $term;
}
    sort($sort_terms_by_children_count);

return $sort_terms_by_children_count;
}

and use it like:

$terms = get_terms('product_cat');
$terms = $sort_terms_by_children_count($terms);

It doesn't work, outputs only one term.

antonimac
  • 35
  • 3

1 Answers1

0

Try Like This

function sort_terms_by_children_count ( $terms ) {
    $sort_terms_by_children_count = array();
    $i=0;
    foreach($terms as $term) {      
        if($term->parent == '0'){
            $term_id = $term->term_id; 
            $taxonomy_name = $term->taxonomy; 
            $countchildren = count (get_term_children( $term_id, $taxonomy_name )); 
            $sort_terms_by_children_count[$i] = $countchildren;         
            $i +=1;
        }                   
    }       
    return $sort_terms_by_children_count;
}
$terms = get_terms('product_cat');                          
$terms = sort_terms_by_children_count($terms);
Nidhi Patel
  • 386
  • 1
  • 6
  • Can you check by debug it? from where you get blank array? It is work for me. – Nidhi Patel Sep 18 '19 at 13:55
  • Notice: Trying to get property 'name' of non-object. if( ! empty( $terms ) && ! is_wp_error( $terms ) ) { foreach( $terms as $term ) { echo $term->name; } } – antonimac Sep 18 '19 at 14:34
  • that's mean you are not even get_terms('product_cat') which is not pass in the function sort_terms_by_children_count(). so get this notice. – Nidhi Patel Sep 19 '19 at 06:25
  • Try to get_terms like this $terms = get_terms([ 'taxonomy' => 'product_cat', 'hide_empty' => false, ]); – Nidhi Patel Sep 19 '19 at 06:31