0
我想知道如何檢查當前的單個帖子或當前類別是否爲任何深度的某個類別的子類。如何檢查當前的帖子或類別是否是某個類別的後代?
例如:
Cat1
>Cat2
>Cat3
>Cat4
>Post1
檢查Post1
是Cat1
孩子,並檢查是否Cat4
是Cat1
我想知道如何檢查當前的單個帖子或當前類別是否爲任何深度的某個類別的子類。如何檢查當前的帖子或類別是否是某個類別的後代?
例如:
Cat1
>Cat2
>Cat3
>Cat4
>Post1
檢查Post1
是Cat1
孩子,並檢查是否Cat4
是Cat1
該函數返回的孩子true
在上述情況。否則爲false
。
<?php
function post_or_category_descendant_of($category_id) {
if(is_category() && (is_category($category_id) || cat_is_ancestor_of($category_id, get_queried_object()))) {
return true;
} else if(is_single()){
$post_id = get_queried_object()->id;
$post_categories = get_the_category($post_id);
$post_cat_ids = array();
foreach($post_categories as $pc) {
$post_cat_ids[] = $pc->cat_ID;
}
$args = array('child_of' => $category_id, 'fields' => 'ids');
$target_cat_ids = get_categories($args);
$target_cat_ids[] = $category_id;
if(array_intersect($post_cat_ids, $target_cat_ids)) {
return true;
} else {
return false;
}
} else {
return false;
}
}