0

I'm using get_terms() to search through WP categories. I'm trying to order them all by name. The code below doesn't work, apparently because there are multiple levels of child categories involved. How do I sort everything by name (whether they are parent or child categories)?

$searchedterms = get_terms( 'category', array(
    'name__like' => $s,
    'orderby' => 'name',
    'order'   => 'ASC',
    'hide_empty' => true
) );

Example:

Alpha (parent)

  • Gamma (level 1 child)

    • Phi (level 2 child)

Beta (parent)

  • Epsilon (level 1 child)

    • Kappa (level 2 child)

Zeta (parent)

should be returned as Alpha, Beta, Epsilon, Gamma, Kappa, Phi, Zeta.

8
  • 1
    I have tested the code it is working perfectly also with child categories. Can you describe more what is the $s value ? Sep 26 '16 at 0:17
  • The $s value is a search term. If you just define $s = 'smthg' and your categories are called "A smthg", "B smthg", "smthg2", etc.. then it will return those results. The parent categories seem to be ordered alphabetically, and child categories under those parent categories too, eg. (A category, AA child category, AB child category, B category, BA child category, BB child category) but I would need them to be "globally" ordered (A category, AA child category, AB child category, BA child category, etc..).
    – Pim
    Sep 26 '16 at 0:30
  • thanks for your response. Can you provide some real categories example to understand it in the better way? Sorry :( Sep 26 '16 at 0:39
  • 1
    I've just tested it here too, and the correct order as you describe is returned regardless of child relationship. Sep 26 '16 at 2:22
  • 1
    Adding another data point, the code posted works for me too. The terms are returned in order alpha ASC regardless of parent/child relationship & depth. I'm using categories named Alpha search, Beta search, etc. (Appended ` search` for testing) The categories are nested as described in the original question. It might be worth checking to see if any code in your theme/plugins uses the get_terms or get_terms_orderby hooks which could be altering results. Oct 2 '16 at 23:21
0

Thank you for all the comments! With your help I managed to rule out a standard Wordpress issue. I couldn't find the culprit (As @DaveRomsey suggested, it could be one of the get_terms or get_terms_orderby hooks altering results). In any case, I solved it by sorting the array:

$searchedterms = get_terms( 'category', array(
    'name__like' => $s,
    'orderby' => 'name',
    'order'   => 'ASC',
    'hide_empty' => true
) ); 
function cmp($a, $b){
    return strcmp($a->name, $b->name);
}
usort($searchedterms, "cmp");

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.