WordPress wp_query $ value = ALL

时间:2016-12-09 21:30:57

标签: php wordpress

我使用的WP_Query非常有效。现在我想添加用户不能过滤的能力" cat"或" city"。

所以我可以通过像#34; *"这样的特殊字符来指定$ category。或"%"到了一天"所有价值观"?我现在没找到它......我应该用另一种方式吗?感谢

  $args = array(
  'post_type' => 'post',
  'cat'     => $category,
  'meta_query' => array(
    array(
      'key'     => 'usp-custom-rdvp_city',
      'value'   => $city,
      'compare' => 'LIKE',
    ),
    array(
      'relation' => 'OR',
      array(
        'key' => 'usp-custom-rdvp_date_event_start',
        'value'   => array( $fromDate, $toDate),
        'type'    => 'DATE',
        'compare' => 'BETWEEN',
      ),
      array(
        'key' => 'usp-custom-rdvp_date_event_end',
        'value'   => array( $fromDate, $toDate),
        'type'    => 'DATE',
        'compare' => 'BETWEEN',
      ),
    ),
  ),
);

1 个答案:

答案 0 :(得分:2)

按类别过滤

  

所以我可以通过像#34; *"这样的特殊字符来指定$ category。或"%"到了一天"所有值"?

没有。相反,当您想要所有类别时,您不希望包含cat参数。好的,所以想一想。如何在一段代码中实现一个/或查询参数?

如果指定了类别,则动态添加cat参数

if ( $category ) {
    $args['cat'] = $category;
}

这个城市怎么样?

使用与上述类别相同的方法。如果有城市,则添加该城市的元查询。

if ( $city ) {
    $args['meta_query'][] = array(
        'key'     => 'usp-custom-rdvp_city',
        'value'   => $city,
        'compare' => 'LIKE',
    );
}

完成参数

让我们把它们放在一起。

$args = array(
    'meta_query' => array(
        array(
            'relation' => 'OR',
            array(
                'key'     => 'usp-custom-rdvp_date_event_start',
                'value'   => array( $fromDate, $toDate ),
                'type'    => 'DATE',
                'compare' => 'BETWEEN',
            ),
            array(
                'key'     => 'usp-custom-rdvp_date_event_end',
                'value'   => array( $fromDate, $toDate ),
                'type'    => 'DATE',
                'compare' => 'BETWEEN',
            ),
        ),
    ),      
);

if ( $category ) {
    $args['cat'] = $category;
}

if ( $city ) {
    $args['meta_query'][] = array(
        'key'     => 'usp-custom-rdvp_city',
        'value'   => $city,
        'compare' => 'LIKE',
    );
}

顺便说一句,您不需要指定'post_type' => 'post',因为它默认设置为post