Instead of prefetching post IDs to include or exclude via the searchwp_include or searchwp_exclude filters, you can directly integrate a meta_query into SearchWP's main search algorithm achieving the same result, but offloading the need to pass a (potentially huge) array of post IDs to include or exclude.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* In this particular implementation I am looking to limit the search results pool based on an | |
* additional form field I have set up that allows people to search entries based on the number | |
* of bedrooms, which is stored as post_meta with a meta_key of listing_bedrooms | |
*/ | |
function my_searchwp_query_join( $sql, $engine ) { | |
global $wpdb; | |
$meta_query_args = array( | |
array( | |
'key' => 'listing_bedrooms', | |
'value' => isset( $_GET["beds"] ) ? absint( $_GET["beds"] ) : 0, | |
'compare' => '>=', | |
"type" => "NUMERIC", | |
) | |
); | |
$meta_query = new WP_Meta_Query( $meta_query_args ); | |
$mq_sql = $meta_query->get_sql( | |
'post', | |
$wpdb->posts, | |
'ID', | |
null | |
); | |
return $sql . $mq_sql['join']; | |
} | |
add_filter( 'searchwp_query_main_join', 'my_searchwp_query_join', 10, 2 ); | |
function my_searchwp_query_conditions( $sql, $engine ) { | |
global $wpdb; | |
$meta_query_args = array( | |
array( | |
'key' => 'listing_bedrooms', | |
'value' => isset( $_GET["beds"] ) ? absint( $_GET["beds"] ) : 0, | |
'compare' => '>=', | |
"type" => "NUMERIC", | |
) | |
); | |
$meta_query = new WP_Meta_Query( $meta_query_args ); | |
$mq_sql = $meta_query->get_sql( | |
'post', | |
$wpdb->posts, | |
'ID', | |
null | |
); | |
return $sql . $mq_sql['where']; | |
} | |
add_filter( 'searchwp_where', 'my_searchwp_query_conditions', 10, 2 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi! This worked great! Just wanted to ask if I can do this based on post type?
To explain, I have a custom field for the media/attachment post type. Basically a toggle to include or not include the PDFs in search.
So what I want to do is to still have a full search (post, pages, attachments), but when it comes to attachments, will filter only the ones tagged to be included in search. I tried the above, but of course, since posts and pages don't have that meta key/value, they also get excluded.
Just wanted to know if you have any thoughts on doing that kind of filter? Working on some other approaches, but maybe you guys already encountered a similar situation before. Thanks!