Question

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?

Was it helpful?

Solution

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

OTHER TIPS

Have a look into get_category_parents()

I dont know the full structure of your code but below is a little bit of code to help get you started but you may need to tweak it. Im not exactly sure if itll work.

$parents = explode('/', get_category_parents( $id ));
if(!isset($parents)) {
    if(in_category($id)) { 
        include 'special-single-page.php'; 
    }
} else {
    if(in_category($parents[0])) { 
        include 'special-single-page.php'; 
    }
}

or something along those lines.

Have a bit of a read up and you could probably find a better way to do it. http://codex.wordpress.org/Function_Reference/get_category_parents

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top