wordpress query_posts to look at meta info
I am looking to run a query with query_posts that lets me look at meta_fields. I have done this once before and achieved the result I wanted but now for some reason adding an extra field into the equation returns nothing.
The query below returns all attachments
where the lottery_year
is equal to $y
, and obviously $y
can be 2011
or earlier.
Now my next step I want to bring in another meta_field
called photo_technique
and give that one a value.
Question, how do I do that?
$querystr = "
SELECT $wpdb->posts.*
FROM $wpdb->posts
LEFT JOIN $wpdb->postmeta ON ($wpdb->posts.ID = $wpdb->postmeta.post_id)
WHERE ($wpdb->postmeta.meta_key = 'lottery_year' AND $wpdb->postmeta.meta_value = $y)
AND $wpdb->posts.p开发者_高级运维ost_type = 'attachment'
ORDER BY $wpdb->postmeta.meta_value ASC
LIMIT 100
";
If you whant to display posts that have either lottery_year = $y
( or ) photo_technique = $x
, you could use :
$querystr = "
SELECT $wpdb->posts.*
FROM $wpdb->posts
LEFT JOIN $wpdb->postmeta ON ($wpdb->posts.ID = $wpdb->postmeta.post_id)
WHERE ($wpdb->postmeta.meta_key = 'lottery_year' AND $wpdb->postmeta.meta_value = $y) OR ($wpdb->postmeta.meta_key = 'photo_technique' AND $wpdb->postmeta.meta_value = $x)
AND $wpdb->posts.post_type = 'attachment'
ORDER BY $wpdb->postmeta.meta_value ASC
LIMIT 100
";
Edit
If you whant to display results that have both lottery_year = $y
( AND ) photo_technique = $x
, you could use the following query :
$querystr = "
SELECT
$wpdb->posts.*
FROM
$wpdb->posts
INNER JOIN $wpdb->postmeta ON
$wpdb->posts.ID = $wpdb->postmeta.post_id
AND $wpdb->postmeta.meta_key IN ( 'lottery_year', 'photo_technique' )
AND $wpdb->postmeta.meta_value IN ( '$y', '$x' )
WHERE $wpdb->posts.post_type = 'attachment'
GROUP BY $wpdb->posts.ID
HAVING COUNT(1) = 2
ORDER BY $wpdb->postmeta.meta_value ASC
LIMIT 100
";
Edit
The last query ( the AND one ) will fail in some circumstances. For example you whant
lottery_year = $y AND photo_technique = $x
, but it will allso return results that have the $x and $y switched like : lottery_year = $x AND photo_technique = $y
, it realy depends when you can rely on it or not, like do you have a photo_technique that is called for example '2001' ( witch could pass as a lottery_year too ) . Please be carefull with it or ask this question on dba.stackexchange.com or wordpress.stackexchange.com .
精彩评论