最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

wp query - Is it possible to add relation between meta_query and tax_query?

programmeradmin2浏览0评论

I have custom post type with some ACF fields. I use ACF for extra properties of entity, and I use native wordpress taxonomies too for base category of entity. So I need to build query with meta_query and tax_query same time. It looks like:

WP_Query {
  "meta_query" => {
    "relation" => "OR",
    [
      "key" => "rating",
      "compare" => "LIKE",
      "value" => "AA"
    ]
  },

  "tax_query" => {
    "relation" => "OR",
    [
      "taxonomy" =>"currencies",
      "field" =>"slug",
      "terms" => [
        "eur",
        "usd"
      ],
      "operator" => "IN"
    ]
  }
}

If I searching only by taxonomies or only by meta-fields, all works fine. But how searching by taxonomies OR by meta-fields (by default, Wordpress use AND relation, i.e. post will finded only if all sub-queries will return true)? I.e. I need add relation between two type of queries in main WP_Query object.

Any suggestions?

I have custom post type with some ACF fields. I use ACF for extra properties of entity, and I use native wordpress taxonomies too for base category of entity. So I need to build query with meta_query and tax_query same time. It looks like:

WP_Query {
  "meta_query" => {
    "relation" => "OR",
    [
      "key" => "rating",
      "compare" => "LIKE",
      "value" => "AA"
    ]
  },

  "tax_query" => {
    "relation" => "OR",
    [
      "taxonomy" =>"currencies",
      "field" =>"slug",
      "terms" => [
        "eur",
        "usd"
      ],
      "operator" => "IN"
    ]
  }
}

If I searching only by taxonomies or only by meta-fields, all works fine. But how searching by taxonomies OR by meta-fields (by default, Wordpress use AND relation, i.e. post will finded only if all sub-queries will return true)? I.e. I need add relation between two type of queries in main WP_Query object.

Any suggestions?

Share Improve this question asked Oct 13, 2017 at 12:32 RaymondRaymond 11 bronze badge
Add a comment  | 

1 Answer 1

Reset to default 1

This is not possible with the WP_Query. You can specify relationship inside the tax query and inside the meta query, but, you can't have the query where meta and tax query are connected by OR.

You can always build the SQL query the way you want it, not relying on the WP_Query at all to filter posts exactly the way you want it. Or, you can use two WP_Query objects, one with meta_query, other with tax_query, and merge the results. In case you have a lot of posts, or you need pagination, that will be a challenge to make optimized.

发布评论

评论列表(0)

  1. 暂无评论