I need to query wordpress posts returning results that could be matched either by the category OR custom field. Using the below code only returns results if they are matched by the category AND custom field. I need to find matches where it could be matched by either query, so an “OR” result but doesn’t seem to work.
Can anyone help?
$args = array(
'post_type' => 'post',
'tax_query' => array(
'relation' => 'OR',
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => array( 'arts','food' ),
'operator' => 'IN'
)
),
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'birth_city',
'value' => 'London',
'compare' => 'IN',
),
)
);
Version 0.2
Here’s a simplification of my previous answer – I hope you don’t mind me adding it as a new answer, to avoid confusion with my previous one.
Here I use the WordPress functions
get_meta_sql()
andget_tax_sql()
, to modify theWHERE
part of the SQL generated byWP_Query()
:Here’s the first attempt to solve your problem. I worked within the following restrictions:
WP_Query
WP_Tax_Query
andWP_Meta_Query
preg_replace
/str_replace
on the SQL query.This is maybe too restrict, but it’s a challange 😉
So you could try:
where we introduce the new parameter
meta_or_tax
:will give you the normal
WP_Query
behaviour andwill allow you to get
OR
instead of the defaultAND
between the tax query and the meta query.The new
WPSE_OR_Query
class is defined as:Here’s an example of the normal SQL:
and the SQL of the modified version:
This can of course be refined much more and you can hopefully extend it further to your needs.
Hope this help.
I failed to find a way of how to do it with WP_Query, but if it helps, here is how to manually write the query, it looks ugly but if that is the only way it will serve the purpose: