Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to display subcategories in Category pages in WordPress

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 .= '
            
  • term_id ).'" title="'.$subcat->description.'">'.$subcat->name.'
  • '; } echo "
      $items
    "; } 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.

    The post How to display subcategories in Category pages in WordPress appeared first on webroom.



    This post first appeared on Sharing With You How To Do And Change Things In WordPress And WooCommerce., please read the originial post: here

    Share the post

    How to display subcategories in Category pages in WordPress

    ×

    Subscribe to Sharing With You How To Do And Change Things In Wordpress And Woocommerce.

    Get updates delivered right to your inbox!

    Thank you for your subscription

    ×