WordPress TAX_QUERY“和”运算符未按预期运行

时间:2016-08-24 作者:dkeeling

我有一个自定义的帖子类型image 使用名为image_tag (它的层次结构类似于类别)。以下是一些可能使用的标签示例:

Structure (id: 25)
- House (id: 56)
- Skyscraper
Nature
- Animal
- Plant (id: 41)
因此,我想通过选择多个标记和“and”操作符来深入查看图像。例如,查找具有plants和houses

$query_args = array(
  \'post_type\' => \'image\',
  \'tax_query\' => array(
    array(
      \'taxonomy\' => \'image_tag\',
      \'terms\' => array(41, 56),    // IDs of "plant" and "house"
      \'operator\' => \'and\',
    ),
  ),
);
这很好,当我尝试包含父项时,问题就开始了,例如:

$query_args = array(
  \'post_type\' => \'image\',
  \'tax_query\' => array(
    array(
      \'taxonomy\' => \'image_tag\',
      \'terms\' => array(25, 41),    // IDs of "structure" and "plant"
      \'operator\' => \'and\',
    ),
  ),
);
然后我就没有结果了。我猜是因为我使用了“and”操作符,所以Wordpress不包括“Structure”术语的子项。有没有人知道我如何才能做到这一点,或者有其他解决方案来实现这一点?

1 个回复
最合适的回答,由SO网友:Jeff 整理而成

未测试,但请试一试

\'tax_query\' => array(
   \'relation\' => \'AND\',
    array(
      \'taxonomy\' => \'image_tag\',
      \'field\'    => \'term_id\',
      \'terms\'    => 25,
      \'operator\' => \'IN\',
    ),
    array(
      \'taxonomy\' => \'image_tag\',
      \'field\'    => \'term_id\',
      \'terms\'    => 41,
      \'operator\' => \'IN\',
    )
  ),

\'tax_query\' => array(
   \'relation\' => \'AND\',
    array(
      \'taxonomy\' => \'image_tag\',
      \'field\'    => \'term_id\',
      \'terms\'    => array(25,41),
      \'operator\' => \'IN\',
    ),
  ),