29

How can I get all subcategories from a certain category?

1

2 Answers 2

39

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>';  
}
4
  • 7
    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, 2011 at 14:49
  • 2
    I agree that get_terms() might be better. Apr 4, 2016 at 14:08
  • 1
    @t31os - could you post an answer using get_terms please?
    – vsync
    Mar 30, 2018 at 20:23
  • 1
    please note, by default, this will not get you categories that has no post associated with them. use hide_empty => false to get all categories (as per the recent version of wordpress) Feb 4, 2020 at 14:06
0

For custom post types "categories" use get_terms().

(Altering @Bainternet's answer)

            $categories = get_terms( array(
                'taxonomy' => 'product_cat',
                'hide_empty' => false,
                'parent' => 17 // or 
                //'child_of' => 17 // to target not only direct children
            ) );
            
            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>';  
            }

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