Styling single.php dynamically by it's parent category in Wordpress

I'm developing a site using Wordpress which uses Categories for main sections with sub categories. Each main section is styled differently so I'm using the parent category slug for each sub category to add an id to the body tag. This works fine and allows all sub category pages to be styled the same as their parent category.

My issue is when you load a single post from a sub category page it uses the single.php template and I need to load the posts parent category slug into the body tag as an id so I can style the post in the same way as it's category page.

As an example the sort of structure I have is News as a parent category with Press Releases and Latest News as sub cats.

Help much appreciated!

Comments


  • Thunder

    Thanks for the quick answers.

    Eric, I used your idea and expanded upon it to get what I need. Might not be the cleanest way to do it but it works!

    I added this function:

    function get_cat_slug($cat_id) {
        $cat_id = (int) $cat_id;
        $category = &get_category($cat_id);
        return $category->slug;
    }
    

    Then used this code to get the parent Id and echo out the slug:

    $getcategory = get_the_category() ;
    $parentcatid = $getcategory[0]->category_parent;
    echo get_cat_slug($parentcatid);
    

    That's done the trick.

  • Sophia

    You just need to call get_the_category() to get a structure describing the category. One of the members of that structure is the ID of the parent category. You can then call get_the_category() again to get the info you need (like the name) on the parent cateogry. See:

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

Add Comment