Skip to content

Instantly share code, notes, and snippets.

@ChrisFlannagan
Created April 18, 2018 17:30
Show Gist options
  • Save ChrisFlannagan/7c0ae5510482a9cea9fb488c7f088fca to your computer and use it in GitHub Desktop.
Save ChrisFlannagan/7c0ae5510482a9cea9fb488c7f088fca to your computer and use it in GitHub Desktop.
<?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