You can do this using custom template and template_include
filter.
category-parent.php
and category-sub.php
both are not required. One can be category.php
for parent categories and for child categories, you can use custom-category-child.php
as category-sub.php
is reserved for default hierarchy.
- First create a template file in theme
custom-category-child.php
- Then add this code to your theme
functions.php
Update: As Pieter suggested we can use category_template
instead of template_include
to save few lines. Additionally we should return current template when our custom template file is missing!
Read inline comments
add_filter('category_template', 'custom_cat_templates');
/**
* Create custom template for child categroies
* @param type $template
* @return type
*/
function custom_cat_templates($template) {
$category = get_category(get_queried_object_id()); //Get the ID for current queried category
if ( $category->category_parent > 0 ) { //Check if it child category
$sub_category_template = locate_template('custom-category-child.php'); //return our custom template
$template = !empty($sub_category_template) ? $sub_category_template : $template; //return default template if custom templaet missing
}
return $template;
}