Skip to content

Instantly share code, notes, and snippets.

@code26
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save code26/8ce362907cc7d4341de8 to your computer and use it in GitHub Desktop.
Save code26/8ce362907cc7d4341de8 to your computer and use it in GitHub Desktop.
Automatic template selector for Wordpress Child/Ancestor Categories
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