Friday, September 16, 2011

WordPress - Template for Parent Slug

WordPress allows you to create special template files for each category. You can name these theme template files cateogry-ID.php or category-SLUG.php, which is nice. However, if you are viewing a category and it does not have its own template, WordPress doesn't look for a parent template file. It just skips that. In lui of creating a template file for every child category (which would be a real pain), I found a nice script that I've edited and improved to provide expanded support (it didn't support slugs in the template name).

 Place this in your functions.php file:
// Use a parent category slug if it exists
function child_force_category_template($template) {
	$cat = get_query_var('cat');
	$category = get_category($cat);

	if ( file_exists(TEMPLATEPATH . '/category-' . $category->cat_ID . '.php') ) {
		$cat_template = TEMPLATEPATH . '/category-' . $category ->cat_ID . '.php';
		
	} elseif ( file_exists(TEMPLATEPATH . '/category-' . $category->slug . '.php') ) {
		$cat_template = TEMPLATEPATH . '/category-' . $category ->slug . '.php';
		
	} elseif ( file_exists(TEMPLATEPATH . '/category-' . $category->category_parent . '.php') ) {
		$cat_template = TEMPLATEPATH . '/category-' . $category->category_parent . '.php';
		
	} else {
		// Get Parent Slug
		$cat_parent = get_category($category->category_parent);
		
		if ( file_exists(TEMPLATEPATH . '/category-' . $cat_parent->slug . '.php') ) {
			$cat_template = TEMPLATEPATH . '/category-' . $cat_parent->slug . '.php';
			
		} else {
			$cat_template = $template;
			
		}
		
	}
	
	return $cat_template;
}
add_action('category_template', 'child_force_category_template');

No comments: