Last active
December 2, 2020 16:40
-
-
Save TwistedTabby/6f7fb414717a57026affaac1adc15602 to your computer and use it in GitHub Desktop.
weighting by post_type using ElasticPress
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
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
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.