Sunday, 25 August 2013

posts_where Fails with More than One Custom Field in Query

posts_where Fails with More than One Custom Field in Query References Querying either of the 2 fields individually gives the expected result (posts are displayed). But, when both fields are included in the query (ex = \'foo\' and \'bar\' shown in below example), then no posts are displayed. function do_stuff( ) { global $wpdb; return \" AND ($wpdb->postmeta.meta_key = \'foo\' AND $wpdb->postmeta.meta_value = \'1\') AND ($wpdb->postmeta.meta_key = \'bar\' AND $wpdb->postmeta.meta_value = \'1\')\"; } add_filter( \'posts_where\', \'do_stuff\' ); Here is a print_r of the WP_Query: [query] => Array ( [post_type] => testPostType [pagination] => 1 [posts_per_page] => 10 [paged] => 1 ) [request] => SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts LEFT JOIN wp_postmeta ON wp_posts.ID = wp_postmeta.post_id WHERE 1=1 AND (wp_postmeta.meta_key = \'foo\' AND wp_postmeta.meta_value = \'1\') AND (wp_postmeta.meta_key = \'bar\' AND wp_postmeta.meta_value = \'1\') ORDER BY wp_posts.post_date DESC LIMIT 0, 10 [posts] => Array ( ) ) Have I made a logic error in the sql? How can I get the posts to display as expected?

No comments:

Post a Comment