Change single.php for posts in child of category

Sometimes WordPress can tie you in knots trying to figure out something that should seemingly be simple. In this situation I was searching for a solution to make wordpress check if a single post was in a child category of a specific category and if it was to show a particular single-id.php template. I didn’t want the post to be assigned to both the child category and the parent, that would have been easy!

So that after some trial and error this was the solution that worked. It only works with both functions for some reason.

1) Add this code to functions.php

/* check for child page */
function is_child($pageID) { 
	global $post; 
	if( is_page() && ($post->post_parent==$pageID) ) {
               return true;
	} else { 
               return false; 
	}
}
if ( ! function_exists( 'post_is_in_descendant_category' ) ) {
 function post_is_in_descendant_category( $cats, $_post = null ) {
 foreach ( (array) $cats as $cat ) {
 // get_term_children() accepts integer ID only
 $descendants = get_term_children( (int) $cat, 'category' );
 if ( $descendants && in_category( $descendants, $_post ) )
 return true;
 }
 return false;
 }
}

then in single.php I put:

$post = $wp_query->post;
if(post_is_in_descendant_category('10') ) 
{include (TEMPLATEPATH . '/single-10.php');
}
else if (in_category('staff')) {include (TEMPLATEPATH . '/single-staff.php');
}
else { include (TEMPLATEPATH . '/single-default.php');

}

There’s probably a more elegant solution but this worked for me.

Leave a Reply

Your email address will not be published. Required fields are marked *