WordPress.org

Ready to get started?Download WordPress

Forums

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

  1. mikejongbloet
    Member
    Posted 3 years ago #

    Hi,

    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
    else
        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.

    Cheers

    Mike

  2. Michael Fields
    Themer
    Posted 3 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
    Member
    Posted 3 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!

    Thanks

    Mike

Topic Closed

This topic has been closed to new replies.

About this Topic