WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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

How can I get all subcategories from a certain category?

share|improve this question
up vote 13 down vote accepted

Yes, you can use get_categories() using 'child_of' attribute. For example all sub categories of category with the ID of 17:

$args = array('child_of' => 17);
$categories = get_categories( $args );
foreach($categories as $category) { 
    echo '<p>Category: <a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a> </p> ';
    echo '<p> Description:'. $category->description . '</p>';
    echo '<p> Post Count: '. $category->count . '</p>';  
}

This will get all categories that are descendants (i.e. children & grandchildren).

If you want to display only categories that are direct descendants (i.e. children only) you can use 'parent' attribute.

$args = array('parent' => 17);
$categories = get_categories( $args );
foreach($categories as $category) { 
    echo '<p>Category: <a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a> </p> ';
    echo '<p> Description:'. $category->description . '</p>';
    echo '<p> Post Count: '. $category->count . '</p>';  
}
share|improve this answer
2  
Just a suggestion: With the popularity of custom post types and taxonomies, i feel it would be better to be suggesting get_terms, because this helps familiarise users with general term fetching functions, where as the category functions are somewhat specific to the built-in taxonomy(though not in all cases). You don't have to agree of course, it's just a suggestion... ;) – t31os Mar 30 '11 at 14:49
    
... you still have my +1 in any case ... :) – t31os Mar 30 '11 at 14:50
    
I agree that get_terms() might be better. – Django Reinhardt Apr 4 at 14:08

protected by Community Dec 26 '13 at 13:26

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site.

Would you like to answer one of these unanswered questions instead?

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