Forums

[resolved] get top parent category (3 posts)

  1. jwoodcreative
    Member
    Posted 1 year ago #

    I'm developing a new theme which uses several main parent categories each with child categories and grand-child categories (and possibly great-grand-child categories).

    The user will have the ability to add more sub-categories.

    I want to style each post depending on its top parent.

    Example structure:
    New York
    - NY maps
    - NY social
    - NY music
    - NY art
    Paris
    - Paris maps
    - Paris social
    - Paris music
    - Paris art
    London
    - London maps
    - London social
    - London music
    - London art

    I've tried using the following as single.php to include the correct template file but this only seems to work for the next level parent not the absolute top level.

    <?php
    
    $category = get_the_category();
    $parent = get_cat_name($category[0]->category_parent);
    if ($parent == 'ny' ) {
    	include(TEMPLATEPATH . '/single-ny.php');
    } else if ($parent == 'paris' ) {
    	include(TEMPLATEPATH . '/single-paris.php');
    } else if ($parent == 'london' ) {
    	include(TEMPLATEPATH . '/single-london.php');
    } else  {
    	include(TEMPLATEPATH . '/single-norm.php');
    }
    ?>

    I've been struggling with this for over a day now and I have exhausted all possibilities via google!!

    Please help! There's got to be a way of doing this!

  2. alchymyth
    The Sweeper
    Posted 1 year ago #

    <?php
    $category = get_the_category();
    $cat_tree = get_category_parents($category[0]->term_id, FALSE, ':', TRUE);
    $top_cat = split(':',$cat_tree);
    $parent = $top_cat[0];
    ?>

    http://codex.wordpress.org/Function_Reference/get_category_parents

    imho:
    an obvious weakness of this is that it always only checks the first of the possible many categories of a post (which is by default the category with the lowest id)

  3. jwoodcreative
    Member
    Posted 1 year ago #

    an obvious weakness of this is that it always only checks the first of the possible many categories of a post (which is by default the category with the lowest id)

    Not sure exactly what you mean by the above, but thank you!!!

    This works well for my needs.

Topic Closed

This topic has been closed to new replies.

About this Topic