Skip to content

Instantly share code, notes, and snippets.

@jchristopher
Last active September 9, 2017 01:48
Show Gist options
  • Save jchristopher/9331899 to your computer and use it in GitHub Desktop.
Save jchristopher/9331899 to your computer and use it in GitHub Desktop.
Integrate SearchWP and Jetpack Infinite Scroll
<?php
// Jetpack infinite scroll does it's own WP_Query, so we need to hijack it at runtime
function searchwp_infinite_scroll_query_args( $query_args ) {
if( class_exists( 'SearchWPSearch' ) ) {
$query = get_search_query();
if( empty( $query ) ) {
if( isset( $_GET['query_args']['s'] ) ) {
$query = sanitize_text_field( $_GET['query_args']['s'] );
}
}
if( !empty( $query ) ) {
// piggyback the submitted query args
$searchwp_args = $query_args;
// customize for the SearchWP search class
$searchwp_args['page'] = $query_args['paged'];
$searchwp_args['terms'] = $query;
$searchwp_args['engine'] = 'default'; // search engine name
$searchwp_args['load_posts'] = false; // only want post IDs because we're going to send those back
$searchwp_args['order'] = 'DESC';
// fire the search
$searchwp = new SearchWPSearch( $query_args );
$hijacked_IDs = $searchwp->postIDs;
// overwrite the original query vars to be what we want as per SearchWP
$query_args['post__in'] = $hijacked_IDs;
$query_args['orderby'] = 'post__in';
}
}
return $query_args;
}
add_filter( 'infinite_scroll_query_args', 'searchwp_infinite_scroll_query_args' );
// also ensure the titles are highlighted as well
function my_searchwp_highlight_title( $title, $id ) {
if( class_exists( 'SearchWP_Term_Highlight' ) ) {
$query = get_search_query();
if( empty( $query ) ) {
if( isset( $_GET['query_args']['s'] ) ) {
// Jetpack
$query = sanitize_text_field( $_GET['query_args']['s'] );
}
}
if( !empty( $query ) ) {
$highlighter = new SearchWP_Term_Highlight();
$title = $highlighter->apply_highlight( $title, $query );
unset( $highlighter );
}
}
return $title;
}
add_filter( 'the_title', 'my_searchwp_highlight_title', 10, 2 );
@benlk
Copy link

benlk commented Mar 9, 2016

On lines 29-32, you set something and then immediately unset it:

            $query_args['orderby'] = 'post__in';
            if( isset( $query_args['orderby'] ) ) {
                unset( $query_args['orderby'] );
            }

Is there a particular reason for that?

@jchristopher
Copy link
Author

@benlk I have no idea what I was thinking there, removed!

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