14 Mar, 2010
Custom Template for Parent and Sub Categories (without a plugin) in WordPress
Posted by: Jennifer In: WordPress|WordPress Hacks
When using WordPress as a CMS, I often repurpose the "posts" as other types of content a site may need. For example, news or press releases, or any information that might need the ability to be catgorized and/or tagged (like testimonials). However, this may mean that you need a completely different template for your news page than you would want for your testimonials page.
WordPress gives you the ability to create category specific templates. So let's say your "news" category has an ID of 5 – if you create a category.php page to be used by all the other categories, and also created a category-5.php page – then just your news page will use that template for the category archive page.
But – what if you have a huge handful of subcategories and you want them all to use the same category template as it's parent? (Let's also assume that we can't just make this the default template) Here's what I came up with. Let's say that Testimonials is our category – it has an id of 12. It also has a dozen or so subcategories (for argument's sake, lets say we've sorted our testimonials into groups from what types of companies these testimoinals have come from "Consulting Firms", "Web Host Providers", "Design Firms", etc.
We don't want to duplicate our category template for every subcategory we have. That's a nightmare to manage. So lets do this instead: In your category.php template file – before ANYTHING ELSE – even before you call get_header() – we add the following:
$thecategory = get_category($cat);
if ($thecategory->category_parent == '12' || $thecategory->cat_ID == '12') {
include(TEMPLATEPATH.'/testimonials-template.php');
} else {
/* include... default template file here like we included the "testimonials-template.php - or you can just wrap this around your actual template code... */
}
So what this does is it gets information about the category – if the current category's PARENT is 12 OR we are in fact looking at category 12 – then we pull in that special testimonials-template.php file… Otherwise the other code would be executed. (In the file I was using I just wrapped that around my existing category.php template code…
Please note: I have not tested this on if you have a SUB SUB category – I'm thinking $thecategory->category_parent probably only looks one level above the current category… so keep that in mind.
(I make the note above that this does not include a plugin because when I was trying to get this to work – one solution I had found online involved installing a plugin that kind of messed with my category heirarchy in a way I wasn't crazy about. Personally, I think this is a much simpler solution)
Updated to add: This article was translated to Belorussian here.