Created
June 30, 2020 09:30
-
-
Save roborourke/da7227d78bd697a85cb2d56783a61fa3 to your computer and use it in GitHub Desktop.
ElasticPress query using prefix match
This file contains hidden or 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 | |
/** | |
* Wrapper for WP_Query that performs a prefix search. | |
* | |
* @param string $url The URL string to search for. | |
* @param array $args Args to pass to WP_Query | |
* @return WP_Query | |
*/ | |
function ep_url_prefix_search( string $url, array $args = [] ) : WP_Query { | |
$args['ep_integrate'] = true; | |
$args['url_prefix_search'] = true; | |
$args['s'] = $url; | |
return new WP_Query( $args ); | |
} | |
/** | |
* Filter EP search query to do a prefix search on the permalink. | |
* | |
* @param array $query The current ElasticSearch query. | |
* @param array $args The WP_Query args. | |
* @return array | |
*/ | |
function ep_url_prefix_search_query_args( array $query, array $args ) : array { | |
if ( ! isset( $args['url_prefix_search'] ) ) { | |
return $query; | |
} | |
// Return a simple prefix query. | |
return [ | |
'prefix' => [ | |
// URL decode and trim wildcard chars, prefix query doesn't require them. | |
'permalink' => urldecode( trim( $args['s'], '*' ) ), | |
], | |
]; | |
} | |
add_filter( 'ep_formatted_args_query', 'ep_url_prefix_search_query_args', 11, 2 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment