I recently posted a question about connecting two queries to omit elements found in a second:
Now I am wondering how to look at a number of meta_keys and their corresponding values to achieve something else.
I am essentially building an event system with custom fields, simplified, an event will have:
- Start Date
- End Date
- Ongoing (Yes or No)
These are stored as
-----------
wp_postmeta
-----------
meta_key
meta_value
post_id
e.g.
-----------
wp_postmeta
-----------
Start Date
2011-07-30
10
-----------
wp_postmeta
-----------
End Date
2011-08-30
10
-----------
wp_postmeta
-----------
Ongoing
Yes
10
My confusion lies in trying to look at multiple wp_postmeta entries and connecting them with the appropriate post.
For example, I want to find the posts that:
- Start Date > Today
- End Date > Today
- Ongoing = Yes
Building upon the previous question, I am trying this query:
SELECT * FROM wp_posts, wp_postmeta
WHERE wp_posts.ID = wp_postmeta.post_id
AND wp_posts.ID IN (
SELECT post_id FROM wp_postmeta
WHERE wp_postmeta.meta_key = 'Start Date'
AND wp_postmeta.meta_value > NOW())
AND wp_posts.ID IN (
SELECT post_id FROM wp_postmeta
WHERE wp_postmeta.meta_key = 'Ongoing'
AND wp_postmeta.meta_value = 'Yes')
AND wp_posts.ID IN (
SELECT post_id FROM wp_postmeta
WHERE wp_postmeta.meta_key = 'End Date'
AND wp_postmeta.meta_value > NOW())
Which is not really working.
I feel like there must be a way to find all the related meta_keys and join their values to the post table, so it can be more easily accessed. For example, is it possible to find the meta_value for ‘Start Date’ and join it to the wp_posts with a column title start_date_value or something like that?
Or how should I be approaching this problem instead?
Using the answer from @karevn, I came up with the following code which works exactly as I want:
$query = array(
'category_name' => 'event',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'Start Date',
'value' => $today,
'compare' => '>'
),
array(
'key' => 'End Date',
'value' => $today,
'compare' => '>'
),
array(
'key' => 'Ongoing',
'value' => 'Yes',
'compare' => '='
),
)
);
I think this is a pretty powerful feature of wordpress.
You can use
WP_Queryclass withmeta_queryoption and avoid writing your own SQL at all. See Codex: http://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters. It is supposed to be a better way in WordPress. Your query will look pretty much like this then:The side effect of using this code is that its results may be cached by DB caching plugin.