我已经找了一段时间,但还没有找到适合这个的解决方案。
我希望能够使用 Wordpress 函数"get_posts()"来检索属于两个不同类别的任何帖子(我的意思是 AND 而不是 OR)。如果我用这样的逗号分隔:
'category'=>'1,2';
它似乎检索属于第1类或第2类的帖子,而不是属于第1类和第2类的帖子。如何使用get_posts执行此操作?
我已经将其视为一种解决方案,但它似乎对我不起作用:
'category__and' => array(1,2)
谢谢。
我认为你不能用get_posts()
做到这一点,因为get_posts()
只会调用 1 个查询(没有子查询),你需要一个子查询在这里根据所需的条件确定要跳过哪些行。
您必须遵循以下代码片段:
$desiredCategory = array( 2, 6 );
$finalPostID = array();
$allPosts = get_posts( array('category__and' => $desiredCategory) );
foreach ($allPosts as $postVariable)
{
$categories = get_the_category($postVariable->ID);
if( in_array($desiredCategory, $categories) )
$finalPostID [] = $postVariable;
}
// Now you can use $finalPostID as your collection of posts.