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_typeofbookinwp_posts - has a meta_key of
book_genreand meta_value offictioninwp_postmeta - has a meta_key of
categoryand meta_value of239, 440inwp_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
1has a post_type ofbook, has a meta key/value pair ofbook_genreandfictionand has a meta key/value pair of 'category' and440so should be included using the above query.Post
2has a post_type ofbook, has a meta key/value pair ofbook_genreandfictionand has a meta key/value pair of 'category' and323so should not be included using the above query.
$wpdbquery 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