【问题标题】:WordPress query posts by several taxonomies几种分类法的 WordPress 查询帖子
【发布时间】:2012-10-23 13:06:55
【问题描述】:

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

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

这是我的查询:

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 );

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

如果术语值为空,我如何从查询中排除分类?

【问题讨论】:

    标签: wordpress taxonomy


    【解决方案1】:

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

    $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 参数中。

    【讨论】:

    • Jrod,我也想通了。谢谢,您的解决方案写得更优雅!
    猜你喜欢
    • 2011-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-17
    • 2014-12-05
    • 1970-01-01
    相关资源
    最近更新 更多