Denver Wordpress Design

Sub-Categories Same Category Template as Parent Category WordPress

Here is another WordPress Tip for anyone who is looking to have sub-categories use the same category template as its parent category, rather than having to create separate templates for each category.

[break]
[break]

We needed to accomplish this for a client that wanted a specific header at the top of every category template and wanted the sub-categories to have the same header.  In order to do this we needed code that would automatically search and determine if there was an active category for the parent category.  After a while of searching Google for a solution – this is usually our first step before creating/developing a custom solution, we came across some very helpful code!!

[break]
[break]

In the WordPress Support forums was a terrifically coded WordPress function that accomplished just what we needed.  Again this will automatically assign parent category templates to sub-categories to bypass the auto templating all you need to do is create a category template for the subcategory you need a different category template for.  So here is the code – just add it to your functions.php file.

[break]
[break]

add_action('template_redirect', 'inherit_cat_template');

function inherit_cat_template() {

if (is_category()) {

$catid = get_query_var(‘cat’);

if ( file_exists(TEMPLATEPATH . ‘/category-‘ . $catid . ‘.php’) ) {
include( TEMPLATEPATH . ‘/category-‘ . $catid . ‘.php’);
exit;
}

$cat = &get_category($catid);

$parent = $cat->category_parent;

while ($parent){
$cat = &get_category($parent);
if ( file_exists(TEMPLATEPATH . ‘/category-‘ . $cat->cat_ID . ‘.php’) ) {
include (TEMPLATEPATH . ‘/category-‘ . $cat->cat_ID . ‘.php’);
exit;
}
$parent = $cat->category_parent;
}
}
}

[break]
[break]

Remember to put this function in your Themes function.php file. Thanks for reading!

[break]
[break]

Read the original post here.

[break]
[break]

If you need any help with WordPress themes, plugins, or anything else, hire us for your project and we will help take your WordPress powered site to the next level!