WordPress how to recognise if a post is in a subcategory of specific category
There are a lot of searches and web pages on the Internet for similar things so just to clarify, this article is a solution to the following issue:
How to recognise if a SINGLE POST is in a SUBCATEGORY of a specific PARENT CATEGORY.
Example:
How do you recognise if post A, B and C are in a subcategory of “A TO M” which is in the ‘ALL LETTERS’ parent category.
Add this code to functions.php in your WordPress theme folder:
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;
}
And add this code to your single.php or other file:
$category_name = ‘CATEGORY NAME’;
$category_to_check = get_term_by( ‘name’, $category_name, ‘category’ );
if ( in_category( $category_name ) || post_is_in_descendant_category( $category_to_check->term_id ) ) {DO SOME COOL STUFF
}