WP_QUERY显示除类别X以外的所有帖子,除非它也在Y类别中

时间:2018-12-01 作者:dmoz

我想展示A、B、C、D类的帖子。。。和Y,除了X,除非X中的帖子也在Y中,然后将它们与其余的一起显示。

我可以很简单地隐藏类别X:

$args = array(
    \'post_type\' => \'post\',
    \'posts_per_page\' => 15,
    \'paged\' => $paged,
    \'cat\' => \'-X\',
);
我试过了combine two loops, 一个获取除X之外的所有帖子,另一个获取X和Y中的帖子,但似乎不起作用:

$EverythingButXLoop_args = array(
    \'post_type\' => \'post\',
    \'cat\' => \'-X\',
);
$EverythingButXLoop = new WP_Query( $EverythingButXLoop_args );

$OnlyXwithYLoop_args = array(
    \'post_type\' => \'post\',
    \'category_name\' => \'categoryX+categoryY\',
);
$OnlyXwithYLoop = new WP_Query( $OnlyXwithYLoop_args );

$mainLoop_args = array(
    \'posts_per_page\' => 15,
    \'paged\' => $paged,
);
$mainLoop = new WP_Query( $mainLoop_args );
$mainLoop->posts = array_merge( $EverythingButXLoop->posts, $OnlyXwithYLoop->posts );

//populate post_count count for the loop to work correctly
$mainLoop->post_count = $EverythingButXLoop->post_count + $OnlyXwithYLoop->post_count;
我还考虑过在一个var中获取所有类别ID(而不是列出我的许多其他类别中的每一个),并将其与类别参数一起使用,以排除X中的帖子。。。不知何故,即。\'cat\' => $categoryIDs, \'category__not_in\' => \'X\' 但我认为我仍然面临着最初的问题:excluding X, except when in X and Y

你知道上面的组合技术有什么不起作用,或者我如何用另一种(更好的)方法来实现这一点吗?提前感谢!

1 个回复
SO网友:Maqk

在您的wp_query, 您应该使用NOT IN 我看不到。在你的论点中WP_Query(), 您应该使用category__not_in 而不是cat. 因此,请将代码更改为:

Excluding Single Category

$args = array(
  \'post_type\' => \'post\',
  \'posts_per_page\' => 15,
  \'paged\' => $paged,
  \'category__not_in\' => \'X\', // string
);
如果要排除多个类别,请在数组中指定类别ID的逗号,而不是字符串。检查以下代码

Excluding Multiple Categories and Displaying Posts That are from X and Y

$args = array(
  \'post_type\' => \'post\',
  \'posts_per_page\' => 15,
  \'paged\' => $paged,
  \'category__in\' => array(X,Y), // Array
  \'post__not_in\' => array(X),
);
以下是完整查询:

$args = array(
  \'post_type\' => \'post\',
  \'posts_per_page\' => 15,
  \'paged\' => $paged,
  \'category__in\' => array(X,Y), // Array
  \'post__not_in\' => array(X),
);

$your_query = new WP_Query( $args );
  while( $your_query->have_posts() ):
  $your_query->the_post();
  the_title();
endwhile;

wp_reset_postdata();

Note: Use ID not the category slug or name

相关推荐

WP_DROPDOWN_CATEGORIES-如何在Widget中保存?

我想用wp_dropdown_categories 在自定义小部件中。所有内容都显示得很好,但由于某些原因,无法正确保存。这是form() 和update() 小部件的功能-我做错什么了吗?public function form( $instance ) { /* Set up some default widget settings. */ $defaults = array( \'title\' => \'Classes by Category\' );&#x