Skip to content

Instantly share code, notes, and snippets.

@jchristopher jchristopher/gist:8345294
Last active Apr 15, 2019

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

commented Apr 15, 2019

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
You can’t perform that action at this time.