Last active
August 29, 2015 14:06
-
-
Save code26/8ce362907cc7d4341de8 to your computer and use it in GitHub Desktop.
Automatic template selector for Wordpress Child/Ancestor Categories
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
function jsp_switch_category_template() { | |
if (is_category()) { | |
$ancestors = get_ancestors(get_query_var('cat'),'category'); | |
$catname = get_query_var('category_name'); | |
if ($ancestors) { | |
$templatePath = TEMPLATEPATH . '/'; | |
$prefix = 'category-'; //default page template prefix | |
$ext = '.php'; | |
$appender = '_child'; | |
$parent_id = $ancestors[0]; | |
$parent_obj = get_term_by('id', $parent_id, 'category'); | |
$parent_slug = $parent_obj->slug; | |
$category_template = $prefix.$catname.$ext; //default template | |
$parent_category_template = $prefix.$parent_slug.$ext; //ancestor template | |
$parent_category_child_template = $prefix.$parent_slug.$appender.$ext; //children template | |
$template = file_exists($templatePath.$category_template) ? $templatePath.$category_template : file_exists($templatePath.$parent_category_child_template) ? $templatePath.$parent_category_child_template : $templatePath.$parent_category_template; | |
if (file_exists($template)) { | |
load_template($template); | |
exit; | |
} | |
} else { | |
return true; | |
} | |
} | |
} | |
add_action('template_redirect','jsp_switch_category_template'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment