WordPress is a beautiful cms, from top to bottom, for both the developers or authors. It’s action and filter hooks made the developers life a lot easier who develop custom solutions on top of wordpress. Today I went throuh a problem where I had to define category template for a parent category type, and then had to make sure that all the child categories under that parent must inherit the same template used by the parent category.
Defining template for a particular category is easy. All you have to do is create a file named as “category-.php”. So if your caregory slug is “stores” then the template name will be “category-stores.php” and as soon some viewers come to http://your.wp.app.url/category/stores that particular template will be used to render the request.
Now the problematic part is I need a few subcategories under the “stores” category which must inherit that same template “category-stores.php”, because the look-n-feel and content are mostly similar. And also there is no default template naming convention for the sub categories. So I had to write an action hook which hooks the “template_redirect” action and then renders the same template used by parent category. Here is the code I used inside functions.php
[sourcecode lang=”php”]
add_action(‘template_redirect’, ‘inheritParentTemplate’);
function inheritParentTemplate() {
if (is_category()) {
$catid = get_query_var(‘cat’); //current category id
$category = get_category($catid);
$parent = $category->category_parent; //immediate parent
if ($parent){
$parentCategory = get_category($parent);
if("stores"==$parentCategory->name){
if ( file_exists(TEMPLATEPATH . ‘/category-‘ . $parentCategory->slug . ‘.php’) ) {
include (TEMPLATEPATH . ‘/category-‘ . $parentCategory->slug . ‘.php’);
}
return true;
}
}
}
}
[/sourcecode]
Thats it. From now on, every child category will be rendered using the same template “category-stores.php“.
Shameless Plug
We develop beautiful Admin Panel templates for the web application developers. Our recent product is “Bolt” which is responsive and built on top of Twitter’s bootstrap. Give it a try and let us know how do you like it.