I want to change the default template hierarchy behavior, and force all subcategory level pages that don't have their own category template file to refer to their parent category template file. In my other post, Richard M. gave an excellent answer that solved the problem for an individual subcategory. Does anyone know how to abstract it?
function myTemplateSelect()
{
if (is_category()) {
if (is_category(get_cat_id('projects')) || cat_is_ancestor_of(get_cat_id('projects'), get_query_var('cat'))) {
load_template(TEMPLATEPATH . '/category-projects.php');
exit;
}
}
}
add_action('template_redirect', 'myTemplateSelect');
Thanks in advance.
Connect to your WordPress hosting using an FTP client and then go to /wp-content/themes/your-current-theme/ and upload your category-design. php file to your theme directory. Now, any changes you make to this template will only appear in this particular category's archive page.
Use following code for to get children category of parent category. <? php $parent_cat_arg = array('hide_empty' => false, 'parent' => 0 ); $parent_cat = get_terms('category',$parent_cat_arg);//category name foreach ($parent_cat as $catVal) { echo '<h2>'.
/**
* Iterate up current category hierarchy until a template is found.
*
* @link http://stackoverflow.com/a/3120150/247223
*/
function so_3119961_load_cat_parent_template( $template ) {
if ( basename( $template ) === 'category.php' ) { // No custom template for this specific term, let's find it's parent
$term = get_queried_object();
while ( $term->parent ) {
$term = get_category( $term->parent );
if ( ! $term || is_wp_error( $term ) )
break; // No valid parent
if ( $_template = locate_template( "category-{$term->slug}.php" ) ) {
// Found ya! Let's override $template and get outta here
$template = $_template;
break;
}
}
}
return $template;
}
add_filter( 'category_template', 'so_3119961_load_cat_parent_template' );
This loops up the parent hierarchy until an immediate template is found.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With