Skip to content

Instantly share code, notes, and snippets.

@jchristopher
Last active April 15, 2019 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jchristopher/8345294 to your computer and use it in GitHub Desktop.
Save jchristopher/8345294 to your computer and use it in GitHub Desktop.
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.
<?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 );
@paolosupena
Copy link

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment