Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmslbam/3fb39b1008b7456bfff1069b0631368c to your computer and use it in GitHub Desktop.
Save jmslbam/3fb39b1008b7456bfff1069b0631368c to your computer and use it in GitHub Desktop.
weighting by post_type using ElasticPress
function SetSearchArgs( $formattedArgs, $args = [] ) {
if( isset( $args[ 'post_type' ] ) && ( count( $args[ 'post_type' ] ) > 1 || gettype( $args[ 'post_type' ] ) === 'string' ) ) {
if( gettype( $args[ 'post_type' ] ) === 'array' ) {
$existing_query = $formattedArgs[ 'query' ];
unset( $formattedArgs[ 'query' ] );
$formattedArgs[ 'query' ][ 'function_score' ][ 'query' ] = $existing_query;
$existing_should = $formattedArgs[ 'query' ][ 'function_score' ][ 'query' ][ 'bool' ][ 'should' ];
unset( $formattedArgs[ 'query' ][ 'function_score' ][ 'query' ][ 'bool' ][ 'should' ] );
$formattedArgs[ 'query' ][ 'function_score' ][ 'query' ][ 'bool' ][ 'must' ] = $existing_should;
foreach( $args[ 'post_type' ] as $postType ) {
$formattedArgs[ 'query' ][ 'function_score' ][ 'functions' ][] = [
'filter' => [
'multi_match' => [
'query' => $postType,
'fields' => [
"post_type.raw",
],
],
],
'weight' => (int) [ INT ],
];
}
}
}
$formattedArgs[ 'query' ][ 'function_score' ][ 'score_mode' ] = 'sum';
$formattedArgs[ 'query' ][ 'function_score' ][ 'boost_mode' ] = "multiply";
return $formattedArgs;
}
add_filter( 'ep_formatted_args', 'SetSearchArgs', 300, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment