-
-
Save sardbaba/5013763 to your computer and use it in GitHub Desktop.
An improved version of the original Jared/Gary version which checks for, in order, the presence of:
1) subcategory template ID
2) subcategory template slug
3) parent category ID
4) parent category slug
5) general category (category.php) You can use it in the function.php file of your theme.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Apply a template to all subcategories of a certain parent category. | |
* | |
* Initial work by Jared Atchison. | |
* http://www.jaredatchison.com/2011/10/02/taking-advantage-of-the-template_include-filter/ | |
* | |
* Revisited by GaryJones https://gist.github.com/GaryJones/1258784 | |
* https://gist.github.com/GaryJones/1258784 | |
* | |
* An improved version of the original Jared/Gary version which checks for, in order, the presence of the templates: | |
* 1) category-{subcategory-id}.php | |
* 2) category-{subcategory-slug}.php | |
* 3) category-{parent-id}.php | |
* 4) category-{parent-slug}.php | |
* 5) category.php | |
* | |
* @author sardbaba | |
* | |
* @param string $template Existing path to template file | |
* @return string Potentially amended path to template file | |
*/ | |
function sardbaba_template_include( $template ) { | |
if ( ! is_category() ) { | |
return $template; | |
} | |
$current_cat = get_query_var( 'cat' ); | |
$category_info = get_category( $current_cat ); | |
$base_url = get_stylesheet_directory() . '/category-'; | |
// Check first if exists a subcategory template. | |
$current_cat_tpl_id = $base_url . $current_cat . '.php'; | |
$current_cat_tpl_slug = $base_url . $category_info->slug . '.php'; | |
if ( is_readable( $current_cat_tpl_id ) ) { | |
return $current_cat_tpl_id; | |
} | |
elseif ( is_readable( $current_cat_tpl_slug ) ) { | |
return $current_cat_tpl_slug; | |
} | |
// Check if exists a parent category template. | |
if ( $category_info->parent == 0 ) { | |
// This is a parent template, use the predefined one. | |
return $template; | |
} | |
// The parent category exists, so, check parent template. | |
$parent_cat = get_category( $category_info->parent ); | |
$parent_cat_tpl_id = $base_url . $parent_cat->term_id . '.php'; | |
$parent_cat_tpl_slug = $base_url . $parent_cat->slug . '.php'; | |
if ( is_readable( $parent_cat_tpl_id ) ) { | |
return $parent_cat_tpl_id; | |
} | |
elseif ( is_readable( $parent_cat_tpl_slug ) ) { | |
return $parent_cat_tpl_slug; | |
} | |
// Nothing found, just use the default template. | |
return $template; | |
} | |
add_filter( 'template_include', 'sardbaba_template_include' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment