I'm having some trouble formatting my query to fetch a list of posts from the database based on the value of two meta values. I'm using WordPress 4.9.4 and I need to use $wpdb->get_results()
and not a normal get_posts()
function call with arguments.
Here is what I have so far, but if I try and include the IN
part in the MySQL query, it doesn't return anything but it should return at least one post.
global $wpdb;
$posts = $wpdb->get_results(
$wpdb->prepare(
'SELECT ' . $wpdb->prefix . 'posts.*, ' . $wpdb->prefix . 'postmeta.* FROM ' . $wpdb->prefix . 'posts, ' . $wpdb->prefix . 'postmeta WHERE ' . $wpdb->prefix . 'posts.post_type = %s AND ' . $wpdb->prefix . 'postmeta.post_id = ' . $wpdb->prefix . 'posts.ID AND (' . $wpdb->prefix . 'postmeta.meta_key = %s AND ' . $wpdb->prefix . 'postmeta.meta_value = %s) AND (' . $wpdb->prefix . 'postmeta.meta_key = %s AND ' . $wpdb->prefix . 'postmeta.meta_value IN (%s)) ORDER BY ' . $wpdb->prefix . 'posts.post_title ASC LIMIT %d OFFSET %d',
'book',
'book_genre',
$genre,
'category',
'239, 440',
$limit,
$offset
)
);
The above query should get all posts where:
- the post has a
post_type
ofbook
inwp_posts
- has a meta_key of
book_genre
and meta_value offiction
inwp_postmeta
- has a meta_key of
category
and meta_value of239, 440
inwp_postmeta
- limit results to
xyz
- offset results of
xyz
However, the above query returns a value of null
if I var_dump( $posts );
onto the page, so I imagine that the in part is causing some sort of conflict with the first meta key/value rule, perhaps?
If I remove the IN
part of the query it gets everything as expected minus the filtering of the categories of course that I'd like. The category ids are an array of ids that are converted into a comma-separated string using PHP's implode()
.
For example:
Post
1
has a post_type ofbook
, has a meta key/value pair ofbook_genre
andfiction
and has a meta key/value pair of 'category' and440
so should be included using the above query.Post
2
has a post_type ofbook
, has a meta key/value pair ofbook_genre
andfiction
and has a meta key/value pair of 'category' and323
so should not be included using the above query.
$wpdb
query which is turned into a MySQL query through the WordPress query method. I understand it's a tricky question to ask and answer, but it's one I've not found anything like before, either it's unique or I might have phrased it differently. The gist is how do I write it in a way that selects posts based on two meta key/value pairs. It seems it's written incorrectly to support two. – user7236046