Use template for posts with a particular category grandparent

I have this category structure for my blog posts:

Grandparent Category-> Parent Category -> Category 1, Category 2, Category 3

the post is assigned only to one of the grandchildren category and I’d like to use a specific template for all the categories that has that specific grandparent (I don’t want to assign them to the grandparent category because i don’t want the grandparent to appear in the post list).

function get_custom_cat_template($single_template) {
 global $post;
if ( in_category( 'Grandparent Category' )) {
      $single_template = dirname(__FILE__) . '/single-template.php';
 }
 return $single_template;
}

add_filter( "single_template", "get_custom_cat_template" ) ;

I realized that if the post is not assigned also to the grandparent category the function in_category() doesn’t work, but I’d like to have something that says –

If that post category has that grandparent use this specific template.

Thanks in advance for your help!

1 Answer
1

Let me update your code 🙂

You don’t need to select grandparent category for your post. First we need to get grandparent category name. Here is the function;

function get_grandparents_category_salgur( $id) { 
    $parent = get_term( $id, 'category' ); 
    if ( is_wp_error( $parent ) ) 
        return $parent; 
     if ( $parent->parent && ( $parent->parent != $parent->term_id ) ) { 
        $go_get_gp = get_term( $parent->parent, 'category' );
    }
    $grandparent = get_term( $go_get_gp->parent, 'category' );  
    return $grandparent->name; 
} 

This code will find grandparent category name. After that we can define in your function.

function get_custom_cat_template($single_template) {
    global $post;
    $postcat = get_the_category( $post->ID );
    $grandparent_name = get_grandparents_category_salgur( $postcat[0]->term_id);
        if ( $grandparent_name === 'Grandparent Category' ) {
            $single_template = dirname(__FILE__) . '/single-template.php';
        }
    return $single_template;
}

add_filter( "single_template", "get_custom_cat_template" );

Leave a Comment