[Resolved] Display a list of sub-categories

Home Forums Support Display a list of sub-categories

Viewing 8 posts - 1 through 8 (of 8 total)
  • Author
    Posts
  • #1520300
    Grant

    Hello,

    I would like:

    1. To display a list of subcategories on a page, as hyperlinks.
    2. 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

    #1520663
    David
    Staff
    Customer Support

    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.

    #1520691
    Grant

    Getting the Parent Category to display a list of its children would work fine for me. How could I go about doing that?

    #1520805
    David
    Staff
    Customer Support

    Is this to be displayed on a Static Page ? Or a Category Archive ?

    #1520836
    Grant

    A static page would be preferable.

    #1521499
    David
    Staff
    Customer Support

    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.

    #1523464
    Grant

    Works great, thanks so much, David!

    #1523542
    David
    Staff
    Customer Support

    Awesome – glad to be of help

Viewing 8 posts - 1 through 8 (of 8 total)
  • You must be logged in to reply to this topic.