WordPress通过几种分类法查询帖子

时间:2012-10-23 13:06:55

标签: wordpress taxonomy

我在这个问题上搜索了很多,但找不到任何有用的东西。也许有人可以帮助我!

我有自定义帖子类型'地点'和两个自定义分类“地点区域”和“地点类别”。我正在通过这两个分类法构建一个下拉过滤器。如果过滤器为空并且两个分类法都被选中,那么一切都很好。但是,如果其中一个分类法具有价值而另一个分类法为空,我无法弄清楚如何使其发挥作用。

这是我的疑问:

if(($category == null) && ($area == null)) {

    //Usual query without taxonomy

  } else {
    $args = array(
      'post_type'      => 'place',
      'tax_query' => array(
            array(
                'taxonomy' => 'placecat',
                'field' => 'slug',
                'terms' => $category
            ),
            array(
                'taxonomy' => 'placearea',
                'field' => 'slug',
                'terms' => $area
            )
        )
    );
  }
  $the_query = new WP_Query( $args );

我认为null值将意味着所有的分类术语,但似乎它正在寻找一个不存在的术语并返回空结果。

如果术语值为null,我可以如何从查询中排除分类法?

1 个答案:

答案 0 :(得分:2)

如果您单独检查它们,也可以单独添加它们。

$args['post_type'] = 'place';

if ( $category != null ) {  
    $args['tax_query'][] =  array(
        'taxonomy' => 'placecat',
        'field' => 'slug',
        'terms' => $category
     );
}

if ( $area != null ) {  
    $args['tax_query'][] = array(
        'taxonomy' => 'placearea',
        'field' => 'slug',
        'terms' => $area
     );
}

在这种情况下,如果它们不为空,我们只将它们添加到tax_query参数。

相关问题