在Wordpress中,你不能在循环之外使用“in_category”,所以我创建了一个函数,它可以提供我的文章所在的所有类别,并从中创建一个“is_category”if语句。
我把我的函数放在我的“functions.php”中:
function inCatAlt($catID){
$allCats = get_categories('child_of='.$catID);
$childCats = 'is_category('.$catID.') ';
foreach($allCats as $childCat){
$childCats.= 'or is_category('.$childCat->cat_ID.') ';
};
$allchildCats = trim(trim($childCats, 'or '));
return $allchildCats;
}
并在我的侧边栏中将其称为“单身”等:
echo inCatAlt(13);
这给了我一个字符串:
"is_category(13) or is_category(16) or is_category(15)"
这正是我所需要的,但现在我想评估字符串以在 if 函数中使用它,如下所示:
if(eval(inCatAlt(13))){
do something
}
但这不起作用。 是我评估错误还是问题出在哪里? 如果我将输出复制粘贴到 if 函数中,它就可以正常工作......
我会回答我认为真正的问题。您提出的解决方案是非常糟糕的做法。
试试这个:
$post_categories = wp_get_post_categories( $post_id );
$child_categories = get_categories( array( 'child_of' => $catID ) );
if( count( array_intersect( $post_categories, $child_categories ) ) > 0 )
// The post exists in one or more of the child categories