Skip to content

Instantly share code, notes, and snippets.

@GaryJones
Forked from rogierborst/gist:2786753
Created May 25, 2012 10:04
Show Gist options
  • Save GaryJones/2787095 to your computer and use it in GitHub Desktop.
Save GaryJones/2787095 to your computer and use it in GitHub Desktop.
Using the template_include filter in WordPress
<?php
add_filter( 'template_include', 'ja_template_include' );
/**
* Apply a template to all subcategories of a certain parent category.
*
* @author Rogier Borst
* @author Gary Jones
* @author Jared Atchison
*
* @link https://gist.github.com/gists/2787095 Current version
* @link http://www.jaredatchison.com/2011/10/02/taking-advantage-of-the-template_include-filter/ Original article
*
* @param string $template Existing path to template file
* @return string Amended path to template file, or original template path.
*/
function ja_template_include( $template ) {
if ( ! is_category() )
return $template;
$category_info = get_category( get_query_var( 'cat' ) );
if ( is_wp_error( $category_info ) || 0 == $category_info->parent )
return $template;
$parent_cat = get_category( $category_info->parent );
// Construct a possible file path
$subcat_template_path = get_stylesheet_directory() . '/subcategory-' . $parent_cat->slug . '.php';
// Return that path if a readable file exists. Otherwise, return the normal template
return is_file( $subcat_template_path ) && is_readable( $subcat_template_path ) ? $subcat_template_path : $template;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment