WordPress the_category() reverse order so parents come first?

A template i’m using is calling the_category() to list the categories which a post belongs to. It’s ordering them by default with the child name first then parents. Is there a way to reverse the order so that the categories are listed as Parent, Child, Second Child?

Related posts

Leave a Reply

2 comments

  1. You could filter get_the_terms and modify the results to suit your needs. You will need to add or remove the filter or use a conditional to only modify this where you need it. Here is an example for reversing the order of the retrieved terms.

    function reverse_categories($terms, $id, $taxonomy){
        if($taxonomy == 'category'){
            $terms = array_reverse($terms, true);
        }
        return $terms;
    }
    add_filter('get_the_terms', 'reverse_categories', 10, 3);
    
  2. You can do this with a one-liner without creating a function/filter wherever you may implement get_the_category_list() function:

    implode(', ',array_reverse(explode(',',get_the_category_list(','))))

    Change the implode string to one of your choice if you don’t want “, “.

    I can personally confirm this works in WordPress 3.5 — but i am sure it will work in just about any version of WordpPress since 1.5.2 when get_the_category_list() was introduced.