I need to run the following query via a WP_Query object:
SELECT wp_posts.* FROM wp_posts
LEFT JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id)
INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id )
INNER JOIN wp_postmeta mt1 ON ( wp_posts.ID = mt1.post_id )
WHERE 1=1
AND
(
(
wp_term_relationships.term_taxonomy_id IN (47) /* current season */
AND wp_postmeta.meta_key = 'show_is_creation' AND wp_postmeta.meta_value = '1'
)
OR (
mt1.meta_key = 'show_in_ontour' AND mt1.meta_value = '1'
AND wp_postmeta.meta_key = 'show_is_creation' AND wp_postmeta.meta_value = '1'
)
)
AND wp_posts.post_type = 'show'
AND ((wp_posts.post_status = 'publish'))
GROUP BY wp_posts.ID ORDER BY wp_posts.menu_order ASC;
So, I need to run a Tax query inside a Meta query clause. This does not seem to be possible with the 'meta_query' argument, something like this:
$meta_query = [
'relation' => 'OR',
[
'relation' => 'AND',
'current_season_clause' => [
'tax_query' => [
'taxonomy' => 'season',
'operator' => 'IN',
'terms' => [47],
],
],
'is_creation_clause' => [
'key' => 'show_is_creation',
'compare' => '=',
'value' => 1,
],
],
[
'relation' => 'AND',
'is_creation_clause' => [
'key' => 'show_is_creation',
'compare' => '=',
'value' => 1,
],
'is_ontour_clause' => [
'key' => 'show_in_ontour',
'compare' => '=',
'value' => 1,
],
],
];
What would be the best way to achieve this? (without running a raw SQL query). Should I use a filter to modify the WHERE statement ?
thanks
show_is_creation
and other tags should be stored as a custom taxonomy, which would make your question significantly easier to answer, and the query possibly hundreds of times quicker. Otherwise what you're asking for is going to be very difficult to do, and very heavy on the database server. Likewise with your season value, it should be a custom taxonomy namedseason
. If you ever need to sort/filter posts by something, store the data you're filtering by in a custom taxonomy not post metashow_is_creation
is just a boolean flag. IMO this should not be a taxonomy.show_is_creation
orshow_is_not_creation
. This allows you to make huge performance gains, and makes your queries much simpler to write. Note I'm not advising you make seperate custom taxonomies for each and every value, you only need a single taxonomy then individual terms.