包括某些类别的帖子,但不包括其他类别的帖子

时间:2017-07-16 作者:Riccardo

我无法成功地从某些类别中筛选帖子,同时从其他类别中排除帖子。当用于只包含给定类别的帖子时,该代码工作得非常好。要包含的类别是子类别,排除的类别是主类别(它们不是包含的子类别的父类别)

示例:

1) 同时使用两者category__incategory__not_in 同时

$wpid = get_category_id($_REQUEST[\'param\']);
$cat_arr  = array($wpid);
$args = array( 
   \'category__in\' =>   $cat_arr,
   \'category__not_in\' =>   array(350,351),                
   \'posts_per_page\' => 10,
   \'post_status\' => \'publish\',
   \'suppress_filters\' => 0
);

$the_query = new WP_Query( $args );
while ($the_query -> have_posts()){
.
.
}
2)仅限使用category__in 具有负值:

$wpid = get_category_id($_REQUEST[\'param\']);
$cat_arr  = array($wpid);
array_push($cat_arr, -350, -351);
$args = array( 
   \'category__in\' =>   $cat_arr,              
   \'posts_per_page\' => 10,
   \'post_status\' => \'publish\',
   \'suppress_filters\' => 0
);

$the_query = new WP_Query( $args );
while ($the_query -> have_posts()){
.
.
}

2 个回复
最合适的回答,由SO网友:Jacob Peattie 整理而成

你可以使用Taxonomy Query, 像这样:

$args = array(
    \'tax_query\' => array(
        \'relation\' => \'AND\',
        array(
            \'taxonomy\' => \'category\',
            \'terms\'    => array(),
            \'operator\' => \'IN\'
        ),
        array(
            \'taxonomy\' => \'category\',
            \'terms\'    => array(),
            \'operator\' => \'NOT IN\',
        ),
    ),
);
$query = new WP_Query( $args );
这将查询第一组术语中的帖子,而不是第二组术语中的帖子。

SO网友:Max Yudin

请尝试此代码。但未测试

<?php

$args = array(
    \'tax_query\' => array(
        \'relation\' => \'AND\', // logical relationship between taxonomy arrays
        array( // subcategories to exclude
            \'taxonomy\'      => \'category\',
            \'field\'         => \'term_id\',
            \'terms\'         => array(350, 351),
            \'operator\'      => \'NOT IN\', // exclude
            \'post_parent\'   => 0 // top level only
        ),
        array( // categories to include
            \'taxonomy\'      => \'category\',
            \'field\'         => \'term_id\',
            \'terms\'         => array($cat_arr),
            // \'include_children\' => false
        )
    ),
    \'posts_per_page\' => 10,
    // more lines if needed
);
我省略了suppress_filters 因为它不适合WP_Query.

也许你会想用\'include_children\' => false (在代码中注释掉)如果您不想显示来自$cat_arr 子类别。

结束

相关推荐

Exclude Tags by Array

谢谢你的帮助!。我正在尝试显示所有标记,但以标记(“作者:”)开头的标记除外。我已经知道了如何排除单个标记(只需将其键入exclude参数)。我已经知道了如何排除标记数组(创建了一个数组并手动添加了几个值)。但我还没有弄清楚如何基于get\\u term\\u by填充数组(或者这是否是最好的方法)。<div id=\"tagarea\"> <div class=\"contained\"> <h2>Categories</h2><