最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Order wordpress taxonomy parent terms by their children count

programmeradmin0浏览0评论

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.

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.

Share Improve this question edited Sep 18, 2019 at 13:53 antonimac asked Sep 18, 2019 at 11:01 antonimacantonimac 112 bronze badges 1
  • Welcome to WordPress Development. I hope you find the answer(s) you are looking for. Our site is different from most - if you have not done so yet, consider checking out the tour and help center to find out how things work. – Matthew Brown aka Lord Matt Commented Sep 18, 2019 at 13:23
Add a comment  | 

1 Answer 1

Reset to default 1

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

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

Cheers!

发布评论

评论列表(0)

  1. 暂无评论