Determining whether a category is top-level or not (3 posts)

  1. mikejongbloet
    Posted 5 years ago #


    I've had a look on Google for this issue and can't seem to find any useful information.

    Basically I want to show a different template depending on whether a category is top-level or not.

    Top Level Categories
    Will have a description, and a list of its child categories (if any exist)

    Anything Other Than Top Level Categories
    Will list out the description, and a list of posts (generic wp functionality)

    At the moment I am passing the category ID into a page as a custom field, and using this custom fields data to run a seperate template. Ideally I'd like to run this functionality all within the category.php template and do something like:

    if(top level category)
        show description
        show list of child categories
        show description
        list posts within this category

    But am struggling with how to determine whether the current category is top level or not, there doesn't seem to be any WP conditionals for this.

    Any help appreciated.



  2. Michael Fields
    Posted 5 years ago #

    The following code should do what you need in category.php:

    $sep = 'ยป';
    $parents = get_category_parents( $cat, TRUE, $sep );
    $parents = explode( $sep, trim( $parents, $sep ) );
    if( 1 === count( $parents ) ) {
    	/* No category parents. */
    else {
    	/* One or more parent categories. */
  3. mikejongbloet
    Posted 5 years ago #

    Perfect, I was trying to work something with the get_category_products() function but you beat me to the solution, which i was probably quite far off getting to!



Topic Closed

This topic has been closed to new replies.

About this Topic