WP_Query多种帖子类型和分类

时间:2016-09-29 21:12:11

标签: wordpress post custom-post-type taxonomy

我想从两种帖子类型中获得结果,

1)发布,仅显示' business'踢球者 2)本地新闻,显示所有踢球者

我到目前为止:

$args=array(
'cat' => $my_category_id,
'post_status' => 'publish',
'posts_per_page' => 5,
'post_type' => array('post', 'local-news'),
'tax_query' => array(
      'relation' => 'OR',
   array(
     'taxonomy' => 'postkicker',
      'term' => 'business'
   ),
    array(
     'taxonomy' => 'impactkicker',
   ),
 ),
'orderby'    => 'date',
'order'      => 'DESC'
);

目前没有显示两种帖子类型,有什么建议吗?提前致谢

1 个答案:

答案 0 :(得分:1)

您还需要确保将cpt local-news连接到category分类法,因为您正在尝试通过此分类法进行选择。这是广泛评论的方法,它将满足您的需求。至少如果我清楚地知道你的想法。如果还没有设置类别,则可以将tax_query的主要关系更改为OR而不是AND来输出项目。

$args = array(
    // 'cat' => $my_category_id, // better  replace it with category in tax_query, see below.
    'post_status'    => 'publish',
    'posts_per_page' => 5,
    'post_type'      => array( 'post', 'local-news' ),
    'tax_query'      => array(
        'relation' => 'AND', // we set it to AND because we want all posts of this category i guess.
        array(
            'taxonomy' => 'category',
            'term'     => $my_category_id,
            'field'    => 'term_id',
            'operator' => 'IN', // just to be more explicit.
        ),
        array( // we create nested sub queries which will filter by other 2 taxonomies, which in turn has OR relation.
            'relation' => 'OR',
            array(
                'taxonomy' => 'postkicker',
                'field'    => 'slug',    // by default it's term_id and you are passing in a slug so set it explicitly.
                'term'     => 'business',
                'operator' => 'IN', // just to be more explicit.
            ),
            array(
                'taxonomy' => 'impactkicker',
                'field'    => 'slug',           // set these or not add rule for taxonomy at all.
                'term'     => 'your-term-slug', // same here.
                'operator' => 'IN', // it's a default value, but ou can set 'EXISTS' if you need to check if whatever term of such taxonomy is assigned.
            ),
        ),
    ),
    'orderby'        => 'date',
    'order'          => 'DESC',
);