Skip to content

Instantly share code, notes, and snippets.

@CatEntangler
Last active December 2, 2020 16:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save CatEntangler/6f7fb414717a57026affaac1adc15602 to your computer and use it in GitHub Desktop.
Save CatEntangler/6f7fb414717a57026affaac1adc15602 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 );
@CatEntangler
Copy link
Author

Comments are welcome... I'll try to comment the code on this one for specific "Why are you.." type of things but this was a generified copy/paste of a client project who is in a rush.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment