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;

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.


there should be no need for this function, you could use $args passed to the get_terms. See: https://codex.wordpress.org/es:Function_Reference/get_terms

get_terms('product_cat', array('orderby' => 'count'));


| improve this answer | |
  • I want to order parent terms by their children count. Not by post count. – antonimac Sep 18 '19 at 13:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.