Created
April 18, 2018 17:30
-
-
Save ChrisFlannagan/7c0ae5510482a9cea9fb488c7f088fca to your computer and use it in GitHub Desktop.
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 | |
add_action( 'pre_get_posts', function( $query ) { | |
if ( ! defined( 'REST_REQUEST' ) || ! REST_REQUEST ) { | |
return | |
} | |
if ( is_admin() || ! isset( $query->query['post_type'] ) || $query->query['post_type'] !== 'product' ) { | |
return; | |
} | |
if ( isset( $_GET['search'] ) && ! empty( $_GET['search'] ) && class_exists( '\SWP_Query' ) ) { | |
/** Let's build a SWP_Query and get some search results */ | |
$args = [ | |
's' => $_GET['search'], | |
'fields' => 'ids', | |
'posts_per_page' => $query->get( 'posts_per_page' ), | |
]; | |
if ( ! empty( $query->get( 'tax_query' ) ) ) { | |
$args['tax_query'] = $query->get( 'tax_query' ); | |
} | |
if ( ! empty( $query->get( 'meta_query' ) ) ) { | |
$args['meta_query'] = $query->get( 'meta_query' ); | |
} | |
/** Now we take our search results and punch them into the query */ | |
$swp = new \SWP_Query( $args ); | |
if ( ! empty( $swp->posts ) ) { | |
$query->set( 'post__in', $swp->posts ); | |
// Tell the query it's not a search anymore or we get screwed up results | |
$query->set( 's', '' ); | |
} | |
} | |
}, 1, 1 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment