多个条件不起作用的Wordpress自定义税务查询

时间:2018-04-17 05:43:43

标签: php wordpress woocommerce

我有这个奇怪的功能,在wordpress中无效。

我使用woocomerce,我必须使用以下转储代码基于某些过滤器获取一些产品:

  ["tax_query"]=>
  array(2) {
    [0]=>
    array(4) {
      ["taxonomy"]=>
      string(11) "product_cat"
      ["field"]=>
      string(4) "slug"
      ["terms"]=>
      array(4) {
        [0]=>
        string(3) "running"
        [1]=>
        string(9) "hiking"
      }
      ["operator"]=>
      string(3) "AND"
    }
    [1]=>
    array(4) {
      ["taxonomy"]=>
      string(11) "product_cat"
      ["field"]=>
      string(4) "slug"
      ["terms"]=>
      array(2) {
        [0]=>
        string(5) "nike"
        [1]=>
        string(9) "adidas"
      }
      ["operator"]=>
      string(2) "OR"
    }
  }

对于$args['tax_query'][0],我需要制作AND逻辑。这意味着如果我选择更多复选框,结果必须减少。

对于$args['tax_query'][1],我需要制作OR逻辑。

上述代码的解释是:给我所有用于跑步但也适合徒步旅行的产品,由nike或adidas生产。

以下代码返回0结果。如果我从["operator"]=> 'AND'移除$args['tax_query'][0],它将返回所有结果,就像它只是通过过滤器一样。

最终代码是:

array(6) {
  ["posts_per_page"]=>
  string(2) "12"
  ["post_status"]=>
  string(7) "publish"
  ["post_type"]=>
  string(7) "product"
  ["offset"]=>
  string(1) "0"
  ["tax_query"]=>
  array(2) {
    [0]=>
    array(4) {
      ["taxonomy"]=>
      string(11) "product_cat"
      ["field"]=>
      string(4) "slug"
      ["terms"]=>
      array(3) {
        [0]=>
        string(3) "running"
        [1]=>
        string(9) "hiking"
      }
      ["operator"]=>
      string(3) "AND"
    }
    [1]=>
    array(4) {
      ["taxonomy"]=>
      string(11) "product_cat"
      ["field"]=>
      string(4) "slug"
      ["terms"]=>
      array(2) {
        [0]=>
        string(11) "nike"
        [1]=>
        string(34) "adidas"
      }
      ["operator"]=>
      string(2) "OR"
    }
  }
  ["meta_query"]=>
  NULL
}

对此有何解释或解决方法?

谢谢。

1 个答案:

答案 0 :(得分:0)

您需要先使用 OR 关系,然后 AND

根据需要修改参数,这个解决方案只是一个想法。

使用POSTS

进行测试
// WP_Query arguments
$args = array(
    'post_type'              => array( 'post' ),
    'post_status'            => array( 'publish' ),
    'tax_query'              => array(
        'relation' => 'OR',
        array(
            'taxonomy'         => 'category',
            'terms'            => array( 'Apple', 'Design' ),
            'field'            => 'name',
            'operator'         => 'AND',
        ),
        array(
            'relation' => 'AND',
            array(
                'taxonomy' => 'category',
                'terms' => array('Photography', '   Android'),
                'field' => 'name',
            ),
        ),
    ),
);

// The Query
$query = new WP_Query( $args );

foreach ($query->posts as $key => $post) {
    echo '<pre>';print_r($post->post_title . ' - '. get_the_category_list(','));echo '</pre>';
}