Archived topic
Display a list of sub-categories
7 replies · Started by Grant on November 6, 2020
Hello,
I would like:
- To display a list of subcategories on a page, as hyperlinks.
- When you click the subcategory hyperlink you would then access all of the posts in that particular subcategory (I am using WP Show Posts for this)
Is there an easy way, perhaps a hook, to show a list of subcategories on a page? Maybe there's a WP Show Posts trick I can't work out?
Thanks,
Grant
Hi there,
how would you determine what list of sub categories were to be displayed on a Page?
If you were viewing a Category Archive then it would be possible to get the Parent Category and display a list of its children. But Pages won't have any idea of what sub categories you want displayed.
Getting the Parent Category to display a list of its children would work fine for me. How could I go about doing that?
Is this to be displayed on a Static Page ? Or a Category Archive ?
A static page would be preferable.
Hmmm... you could try creating a Shortcode that displays a list of Sub Categories of the given parent category.
Add this PHP Function to your site:
function display_subcategories( $atts ) {
$atts = shortcode_atts( array(
'category' => null
), $atts );
$parent_cat_slug = get_category_by_slug( $atts['category'] );
$parent_cat_ID = $parent_cat_slug->term_id;
$args = array(
'hierarchical' => 1,
'hide_empty' => 0,
'parent' => $parent_cat_ID,
'taxonomy' => 'category'
);
$subcats = get_categories($args);
ob_start();
echo '<ul class="sub-categories">';
foreach ($subcats as $subcat) {
$link = get_term_link( $subcat->slug, $subcat->taxonomy );
echo '<li><a href="' . $link . '">' . $subcat->name . '</a></li>';
}
echo '</ul>';
return ob_get_clean();
}
add_shortcode( 'subcategory', 'display_subcategories' );
Then you can add the shortcode like so:
[subcategory category="category-slug"]
Change the category-slug to that of the parent category that you want to display the children of.
Works great, thanks so much, David!
Awesome - glad to be of help