Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get_terms() orderby name is not working - wordpress

I'm using wordpress, want first-level taxonomy terms to be ordered by name but below code is not giving me desired result. Here is my code:

$args = array(
    'taxonomy' => 'tax-category', 
    'hide_empty' => 0,
    'hierarchical' => 1,
    'parent' => 0,
    'orderby'=>'name',
    'order' => 'DESC',
    'fields' => 'all',
);
$rs_terms = get_terms('tax-category', $args);

When I'm adding below php sorting, it works perfectly. But want to know why wordpress's default sorting is not working properly:

usort($rs_terms, function($a, $b){
    return strcmp($a->name, $b->name);
});
like image 810
aiddev Avatar asked Jul 06 '17 07:07

aiddev


2 Answers

Showed up here with the same problem, and like others mentioned, the culprit was a plugin related to taxonomy sorting. Category Order and Taxonomy Terms Order, in my case. I deactivated it, and my terms list popped into order.

like image 62
Cory Avatar answered Sep 22 '22 08:09

Cory


Your code should work fine. I had for same problem and I found a hook in my plugin that changed 'orderby' value. It might be the same case.
I suggest you look for a filter function hooked to get_terms() in your plugin/theme.

Possible hooks:

  • terms_clauses
  • get_terms_orderby
  • get_terms_args

EDIT: Before you go scanning the hooks you should try adding 'menu_order' => false to your args, it might do the job for you. There are taxonomies with manual drag&drop sorting (menu_order), so you just need to unable it.

like image 41
Hike Nalbandyan Avatar answered Sep 24 '22 08:09

Hike Nalbandyan