How to use a specific template for a category or tag in single.php

(Jason Tucker) #1

I have a post that has a specific category and tag and I want to be displayed using a specific page template. Is this the best way to go about this (in post.php)? It too bad the WordPress template hierarchy doesn’t allow for this out of the box by naming the page template single-post-categoryname.php

$post = $wp_query->post;
if (is_tag(‘your-tag’)) {
include (TEMPLATEPATH.’/your-custom-post-template.php’);

get_header(); ?>`

(Chetan Chauhan) #2

You can use template_include filter like this

add_filter( 'template_include', 'load_custom_post_template' );
function load_custom_post_template( $template ) {
	if ( has_tag( 'your-tag' ) ) {
		$template = TEMPLATEPATH . '/' . 'your-custom-post-template.php';

	return $template;

(Leland Fiegel) #3

I would do what @chetanchauhan suggested. Your concept is on the right track (with one major caveat, discussed in next paragraph), it would just be kinda messy to include stuff in the template file itself IMO. Plus, this is exactly what the template_include filter is for.

Also note how Chetan uses has_tag instead of is_tag. The has_tag conditional will check if a post has a certain tag, while is_tag will check if a tag archive page (i.e. is being displayed.

You’re checking for the former, so you would want to use has_tag in this case.

If I had to make one suggestion, make sure the function name is prefixed (i.e. yoursite_load_custom_post_template instead of load_custom_post_template).

(Piet) #4

how about using get_template_part()?