Last active
September 9, 2017 01:48
-
-
Save jchristopher/9331899 to your computer and use it in GitHub Desktop.
Integrate SearchWP and Jetpack Infinite Scroll
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 | |
// 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 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
On lines 29-32, you set something and then immediately unset it:
Is there a particular reason for that?