Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Using the template_include filter in WordPress
add_filter( 'template_include', 'ja_template_include' );
* Apply a template to all subcategories of a certain parent category.
* @author Jared Atchison
* @link
* @param string $template Existing path to template file
* @return string Potentially amended path to template file
function ja_template_include( $template ) {
// Parent category (News) ID
$my_parent_category_id = 7;
if ( ! is_category() )
return $template;
// Get category information
$category_info = get_category( get_query_var( 'cat' ) );
if ( $category_info->parent == $my_parent_category_id )
return get_stylesheet_directory_uri() . '/subcategory-news.php';
return $template;

This comment has been minimized.

Copy link

@ericrasch ericrasch commented Mar 25, 2012

Wondering if there's a way to use the slug name on lines 15/23 rather than an ID?


This comment has been minimized.

Copy link
Owner Author

@GaryJones GaryJones commented Mar 25, 2012

@ericrasch - absolutely. If you look at you'll see that there are lots of properties available instead of parent on line 23 - it sounds as though you want to use slug.

Be aware however, that slugs can change (by un-informed but well-meaning clients), as can names, which is why it's usually safer to go with an ID, and add a comment for developers reading the code, as per my example.


This comment has been minimized.

Copy link

@rogierborst rogierborst commented May 25, 2012

Just created a fork that's more dynamic. In this version you hardcode the template file ('/subcategory-news.php') into the function.
You could also check if there's a file called 'subcategory-' + the parent category slug + .php in the theme folder and use that one (like I do in my fork).


This comment has been minimized.

Copy link

@sardbaba sardbaba commented Feb 22, 2013

I've forked to better handle the hierarchical order... see

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment