Home / WordPress / How to display subcategories in Category pages in WordPress

How to display subcategories in Category pages in WordPress

Published On: October 8th, 2021|Categories: WordPress|2 min read|

I was given the task to display all subcategories when a user is in a category. By default you cannot do that in WordPress. There are some plugins that’ll do the work, but it really isn’t neccessary to extra load your website with additional plugins, when you can use this simple function:

function webroomtech_sub_category_list(){
  if(is_category()) {

    $breakpoint = 0;
    $thiscat = get_term( get_query_var('cat') , 'category' );
    $subcategories = get_terms( 'category' , 'parent='.get_query_var('cat') );

    if(empty($subcategories) && $thiscat->parent != 0) {
        $subcategories = get_terms( 'category' , 'parent='.$thiscat->parent.'' );
    }

    $items='';
    if(!empty($subcategories)) {
        foreach($subcategories as $subcat) {
            if($thiscat->term_id == $subcat->term_id) $current = ' current-cat'; else $current = '';
            $items .= '
            <li class="cat-item cat-item-'.$subcat->term_id.$current.'">
                <i class="fas fa-long-arrow-alt-right" style="margin-right:10px"></i> <a href="'.get_category_link( $subcat->term_id ).'" title="'.$subcat->description.'">'.$subcat->name.'</a>
            </li>';
        }
        echo "<ul style='padding: 0;list-style: none;'>$items</ul>";
    }
    unset($subcategories,$subcat,$thiscat,$items);
  }
}

Once I have the function ready, I can use it directly in the category template file or in my case I used it in a shortcode which I put in the layout design of the category page using the theme builder. Ps. a powerful and easy to use page builder is Elegant Theme’s Divi.

// create shortcode to show subcategories as link in parent
function webroomtech_subcategrory() { 
	
    ob_start();
    sub_category_list();
	return ob_get_clean();
	
} 
// register shortcode
add_shortcode('showsubcat', 'webroomtech_subcategrory');

All the code goes in functions.php of your child theme. And that’s it, here’s the result:

Note that the code is for the standart WordPress taxonomy “Category”. You can modify it and use it for any taxonomy, whether it’s custom taxonomy or a standart WordPress tazonomy like “Tags”.

Disclosure: Some of the links in this post are “affiliate links.” This means if you click on the link and purchase the item, I will receive an affiliate commission which helps me running this site.




Related Articles

If you enjoyed reading this, then please explore our other articles below:

More Articles

If you enjoyed reading this, then please explore our other articles below: