Skip to content

Instantly share code, notes, and snippets.

@boonebgorges
Created March 24, 2012 17:47
Show Gist options
  • Save boonebgorges/2185537 to your computer and use it in GitHub Desktop.
Save boonebgorges/2185537 to your computer and use it in GitHub Desktop.
Recursively sort the output of get_categories() in order of parent-child hierarchy
<?php
$categories = get_the_category();
// Assemble a tree of category relationships
// Also re-key the category array for easier
// reference
$category_tree = array();
$keyed_categories = array();
foreach( (array)$categories as $c ) {
$category_tree[$c->cat_ID] = $c->category_parent;
$keyed_categories[$c->cat_ID] = $c;
}
// Now loop through and create a tiered list of
// categories
$tiered_categories = array();
$tier = 0;
// This is the recursive bit
while ( !empty( $category_tree ) ) {
$cats_to_unset = array();
foreach( (array)$category_tree as $cat_id => $cat_parent ) {
if ( !in_array( $cat_parent, array_keys( $category_tree ) ) ) {
$tiered_categories[$tier][] = $cat_id;
$cats_to_unset[] = $cat_id;
}
}
foreach( $cats_to_unset as $ctu ) {
unset( $category_tree[$ctu] );
}
$tier++;
}
// Walk through the tiers to order the cat objects properly
$ordered_categories = array();
foreach( (array)$tiered_categories as $tier ) {
foreach( (array)$tier as $tcat ) {
$ordered_categories[] = $keyed_categories[$tcat];
}
}
// Now you can loop over them and do whatever you want
foreach( (array)$ordered_categories as $oc ) {
echo $oc->cat_name . ' ';
}
?>
@willyfc
Copy link

willyfc commented Apr 29, 2014

thank you very much, it was very helpful to me

@EvanMcEwen
Copy link

Thanks so much! I can't believe this wasn't possible to achieve with a simple parameter to get_the_category(). I thought I was gonna have to write this myself!

@Perotin
Copy link

Perotin commented Nov 29, 2015

Thank you! How to the design the output like this: Category1, Parent category2 / Child1, Category3 ... etc? (coma after the category (except the last), and a slash between parent-child)

@fhott
Copy link

fhott commented Dec 17, 2015

Thanks!

@mehrshaddarzi
Copy link

Thanks :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment