Inside the loop you can make use of wp_get_post_terms()
to return all the terms associated with the specific post. This object returned holds all the terms with all the properties of the specified terms
With that in mind, you can use a foreach
loop to get each term, and then check each term’s parent. For grandchild terms you will need to do some extra checking here to determine the parent or top most level term parent
You can do something like this
$terms = wp_get_post_terms( $post->ID, 'category' );
if ( !empty( $terms ) && !is_wp_error( $terms ) ){
foreach ( $terms as $term ) {
if ( $term->parent == 4 ) {
//Do something if parent is 4
}
}
}
EDIT
To make this work with deeper level categories, you can use get_ancestors()
to get all levels and use in_array()
to test for the specific category ID
You can extend the function as follow:
$terms = wp_get_post_terms( $post->ID, 'category' );
if ( !empty( $terms ) && !is_wp_error( $terms ) ){
foreach ( $terms as $term ) {
if( $term->parent != 4 && $term->parent == 0 )
continue;
if ( $term->parent == 4 || in_array( 4, get_ancestors( $term->term_id, 'category' ) )) {
//Do something if parent ID is 4
} else {
//Do nothing
}
}
}