How to get ordered categories via the wp_get_post_categories() function?

Given the following hierarchy of categories:

  • Planet
    • Continent
      • Country
        • State

When I retrieve them from a Post that has them all using the following code:

Read More
$post_categories = wp_get_post_categories( $post_id );
$cats = array();

foreach($post_categories as $c){
    $cat = get_category( $c );
    $cats[] = array( 'name' => $cat->name, 'slug' => $cat->slug );
}

And echo the results:

echo $cats[0]['name'];
echo $cats[1]['name'];
echo $cats[2]['name'];
echo $cats[3]['name'];

I get them ordered alphabetically, like this:

Continent, Country, Planet, State

But what I actually need is to get them ordered by their hierarchy, like this:

Planet, Continent, Country, State

Any ideas? Thanks in advance!

Related posts

Leave a Reply

2 comments

  1. Found the answer! It’s quite obvious actually, but in case this helps to someone in the same situation, here it is.

    All you need to do is add the following array as the second argument, like this:

    $post_categories = wp_get_post_categories( $post->ID, **array('orderby' => 'term_order', 'order' => 'ASC')**);
    

    That does the trick!

  2. $post_categories = wp_get_post_categories( $post->ID, array(‘orderby’ => ‘term_order’, ‘order’ => ‘ASC’));

    This only return the categories ordered by id ASC, so attention because when you will insert in future another category element on the three for example on the top this function will stop to work because your root element will be the last.