WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Categories & separate sub category templates (3 posts)

  1. Mr_Scientist
    Member
    Posted 1 year ago #

    Hi all,

    I'm currently making a magazine style site with customised templates. I've run into a problem regarding the category > sub-category templates.

    I have two different parent categories which then have a number of sub-categories beneath them. For example -

    Parent Category 1 >
    Sub Category 1 > Posts
    Sub Category 2 > Posts

    Parent Category 2 >
    Sub Category 1 > Posts
    Sub Category 2 > Posts

    I would like to have one template for the parent categories (which outputs links to the sub-categories), this I've managed to achieve. What I can't figure out is how to have a separate template which allows me to display the posts within that specific sub-category. Whilst I realise you can name a template category-slug/id.php I would like just one sub-category template that can be used across all the sub categories. I'm really not sure about how to go about doing this, even after reading the Codex and relentless Googling.

  2. Mr_Scientist
    Member
    Posted 1 year ago #

    I believe I have now solved this problem and the key lies here -

    Place the following code within functions.php -

    function is_subcategory (){
        $cat = get_query_var('cat');
        $category = get_category($cat);
        $category->parent;
        return ( $category->parent == '0' ) ? false : true;
    }

    And this code within the category.php template -

    if ( is_subcategory() ) {
        // do required actions
    }

    The above code was from the WP Mayor website.

    Adjust the statement to become an if/else inside the category.php page. If the category is within a sub-category output the loop to show the posts of that category, else output the subcategories themselves.

  3. praveen68
    Member
    Posted 10 months ago #

    Hi Mr_Scientist. I faced the same situation as yours. Glad to hear you sorted it out.
    I am still stuck where you began. I created separate category-1.php and category-2.php. When i click the category it open the right category with respective posts. But when I click the posts it opens single.php. When in breadcrumbs when I click Category-1 it open in category.php not category-1.php. What is the code I suppose to give in category.php with the if/else. Please guide.
    Thanks

Topic Closed

This topic has been closed to new replies.

About this Topic