• Resolved mrjonnywood

    (@jwoodcreative)


    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!

Viewing 2 replies - 1 through 2 (of 2 total)
  • <?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)

    Thread Starter mrjonnywood

    (@jwoodcreative)

    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.

Viewing 2 replies - 1 through 2 (of 2 total)

The topic ‘get top parent category’ is closed to new replies.