Skip to content

Instantly share code, notes, and snippets.

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

This comment has been minimized.

Copy link

@benlk 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

This comment has been minimized.

Copy link
Owner Author

@jchristopher jchristopher commented May 9, 2016

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