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" );