WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Hello at the moment I'm wondering how I would be able to make this work to post in Hierarchical order within the post loop.

    foreach ((get_the_category()) as $childcat) 
        if (cat_is_ancestor_of('42', $childcat)) 
            echo '<li> <a href="'.get_category_link($childcat->cat_ID).'">'; echo $childcat->cat_name . '</a> </li>'; 

I would like it to output as such:

  • Parent
    • Child
    • Child
      • Grandchild
share|improve this question
up vote 2 down vote accepted

Use wp_list_categories instead,


    $args = array(
    'hierarchical'       => true,
    'child_of'            => 42,   //parent category
    'hide_empty'         => 1,    //hide empty categories (set to 0 to show)



A full list of parameters for wp_list_categories can be found HERE

As you can see its highly customizable simply by adding extra arguements to the array stored in the $args variable that we later pass to the wp_list_categories function.

Note: Adding the child_of => ID argument you can specify the parent ID of the category for which you want to retrieve category terms for. Be aware that if there are no posts in the parent category, it will not show, in which case you may try setting hide_empty => 0 instead.


Well, instead of writing this from scratch myself, Scribu already has thankfully, so please take a look at the following link for more details;


share|improve this answer
Problem with wp_list_categories is it lists all the categories but not like get_the_category that pulls from the current post. – espnicholas Jun 22 '12 at 21:48
Ok sorry, I read your opening sentence differently than that. – userabuser Jun 22 '12 at 21:56
Sorry, I fixed it! – espnicholas Jun 22 '12 at 22:01
Late reply but I forgot to approve, my apology! – espnicholas Sep 6 '12 at 7:58
No problem, enjoy! – userabuser Sep 7 '12 at 14:37

You need to sort the categories to make sure they come in the correct order:

// get categories of post in sorted order
$categories = sortCategories(get_the_category());     

function sortCategories($categories) { // Sorting the category
    usort($categories, "cmpCategories");
    return $categories;

function cmpCategories($category_1,$category_2) { // Sort function
    foreach(get_categories(array("parent" => $category_1->cat_ID)) AS $sub) {
        if($category_2->cat_ID == $sub->cat_ID) return -1;
    return 1;
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.