法典基本上解释了如何做到这一点:
if ( $category_to_check = get_term_by( \'name\', \'fruit\', \'category\' ))
post_is_in_descendant_category($category_to_check->term_id);
https://codex.wordpress.org/Function_Reference/in_category#Testing_if_a_post_is_in_a_descendant_category
将所有这些放在您的功能中,您将拥有:
if ( ! function_exists( \'post_is_in_descendant_category\' ) ) {
function post_is_in_descendant_category( $cats, $_post = null ) {
foreach ( (array) $cats as $cat ) {
if (!absint($cat)) {
// $cat = get_category_by_slug($cat); // option one
$cat = get_term_by(\'slug\',$cat,\'category\'); // option two
// $cat = get_term_by(\'name\',$cat,\'category\'); // option three; by category name, not slug, as in the Codex
if(!$cat) return false;
$cat = $cat->term_id;
}
// get_term_children() accepts integer ID only
$descendants = get_term_children( (int) $cat, \'category\' );
if ( $descendants && in_category( $descendants, $_post ) )
return true;
}
return false;
}
}