在这种情况下,我想做的就是显示一个标题(header)2-如果一篇文章选中了某个类别,则编辑评论。我可能只有“灰熊”,或者可能同时有“灰熊”和它的孩子“灰熊钓鱼”,或者我可能有另一个孩子“灰熊吃东西”,但只要“灰熊”类别被选中,我希望-THEN-语句发生。
我们仍然可以使用在ORIGINAL ANSWER, 但我们会用不同的方式。我们需要得到帖子所属的类别,然后检查灰熊是否在其中
$parent_cat = 1, //Pass the ID, this will ID for \'Grizzly bears\'
$descendants = get_term_descendants( $parent_cat );
$post_terms = get_the_category( get_the_ID() );
$ids = wp_list_pluck( $post_terms, \'term_id\' );
if ( $decendants && !in_array( $parent_cat, $ids ) ) {
if ( has_category( $decendants ) ) {
// Post belongs to parent cat descendants but not parent cat
}
} elseif ( in_array( $parent_cat, $ids ) ) {
// Post belongs to the parent category
} else {
// Post does not belong to parent cat or any of its decendants
}
原始答案你的问题有点难理解,但我会回答我的阅读方式。
如果需要将某个标头应用于顶级术语及其所有子体,可以使用get_terms()
返回给定顶级父级的所有子级
代码前的几个注释:
代码未经测试,可能有缺陷。请确保首先在启用调试的情况下在本地测试此功能
该代码至少需要PHP 5.4
它可能非常冗长,因为我们需要做大量工作才能从顶级术语中获得所有后代。注意,我已经对此进行了解释,但为了提高性能,请确保将ID而不是slug传递给函数,并且不要使用名称代码
function get_term_descendants( $term = \'\', $taxonomy = \'category\' )
{
// First make sure we have a term set, if not, return false
if ( !$term )
return false;
// Validate and sanitize taxonomy
if ( \'category\' !== $taxonomy ) {
$taxonomy = filter_var( $taxonomy, FILTER_SANITIZE_STRING );
// Make sure the taxonomy is valid
if ( !taxonomy_exists( $taxonomy ) )
return false;
// Make sure our taxonomy is hierarchical
if ( !is_taxonomy_hierarchical( $taxonomy ) )
return false;
}
// OK, we have a term and the taxonomy is valid, now we need to validate and sanitize the term
if ( is_numeric( $term ) ) {
$term = filter_var( $term, FILTER_VAILDATE_INT );
} else {
$term_filtered = filter_var( $term, FILTER_SANITIZE_STRING );
$term_object = get_term_by( \'slug\', $term_filtered, $taxonomy );
$term = filter_var( $term_object->term_id, FILTER_VAILDATE_INT );
}
// Everything is sanitized and validated, lets get the term descendants ids
$term_descendants = get_terms( $taxonomy, [\'child_of\' => $term, \'fields\' => \'ids\'] );
// Check if we have terms
if ( !$term_descendants )
return false;
// We have made it, return the descendants
return $descendants;
}
我们的职能get_term_descendants()
现在将保留传递给函数的项的子项ID数组,或者如果传递的项没有子项,则返回false我们现在可以使用我们的函数并将返回的ID数组直接传递给has_category()
NOTE: 您可以将父项ID或slug传递给函数。不要使用名称,因为层次结构术语在不同层次结构中可能有重复的名称。还要注意的是,将slug传递给函数的代价有点高,因为我们将使用get_term_by()
从slug中获取术语ID。为了提高性能,请尝试始终传递ID
$parent_cat = 1, //Pass the ID, can pass the slug, but reread the note above
$descendants = get_term_descendants( $parent_cat );
if ( $decendants ) {
$term_array = array_merge( $parent_cat, $descendants );
} else {
$term_array = $parent_cat;
}
// Now we can check if the post belongs to the parent cat or one of his descendants
if ( has_category( $term_array, $post ) ) {
// Post belongs to parent cat or one of his descendants
} else {
// Post does not belong to the parent or any of his descendants
}