Given the following hierarchy of categories:
- Planet
- Continent
- Country
- State
- Country
- Continent
When I retrieve them from a Post that has them all using the following code:
$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!
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:
That does the trick!
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.