How can I get all subcategories from a certain category?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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 ) . '" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" 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 ) . '" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" 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>';
}
Method 2
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>';
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0