use a single page template for all posts in subcategories in wordpress

advertisements

I have several posts that are under several sub categories of sub categories (3rd level), and of course, one parnet category above all of them.

I want to make a special single.php page for all of the posts, but the

<?php if(in_category($id)) { include 'special-single-page.php'; }

only works for posts directly under that category and not for posts that are in sub categories of sub categories.

Is there a way to include a file for posts that are under several sub categories of the parent category?


Apparently, wordpress has a ready script for this. it goes like this:

<?php if ( in_category( $id ) || post_is_in_descendant_category( $id ) ) {
    // your code goes here
}
?>

but you need to add a function to your theme's function.php file. this is the function to add:

<?php
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;
    }
}
?>

source