Last active
January 27, 2021 20:39
-
-
Save bjorn2404/92da048e91f3b685550e704df5e0b976 to your computer and use it in GitHub Desktop.
ElasticPress exclude post type from "Weight results by date" decay
This file contains 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 | |
/** | |
* Filter the arguments sent to EP query | |
* | |
* @param array $formatted_args Formatted Elasticsearch query | |
* @param array $query_vars Query variables | |
* @param array $query Query part | |
* | |
* @return array | |
*/ | |
function filter_ep_args( $formatted_args, $query_vars, $query ) { | |
// Only apply this to the main search query. | |
if ( ! is_search() && ! is_main_query() ) { | |
return $formatted_args; | |
} | |
// Get the ElasticPress search settings. | |
if ( defined( 'EP_IS_NETWORK' ) && EP_IS_NETWORK ) { | |
$ep_feature_settings = get_site_option( 'ep_feature_settings', [] ); | |
} else { | |
$ep_feature_settings = get_option( 'ep_feature_settings', [] ); | |
} | |
// Make sure "Weight results by date" is enabled. | |
if ( | |
'1' === $ep_feature_settings['search']['decaying_enabled'] && | |
! empty( $formatted_args['query']['function_score']['functions'] ) && | |
is_array( $formatted_args['query']['function_score']['functions'] ) | |
) { | |
// Existing decay definition should be here. | |
$decay = $formatted_args['query']['function_score']['functions'][0]; | |
// Add only the post types that should have the decay applied. | |
$extra_filter = [ | |
'filter' => [ | |
'terms' => [ | |
'post_type.raw' => [ | |
'post_type_1', | |
'post_type_2' | |
], | |
], | |
], | |
]; | |
// Add both decay and the new filter to the query. | |
$formatted_args['query']['function_score']['functions'][0] = array_merge( | |
$extra_filter, | |
$decay | |
); | |
} | |
} | |
add_filter( 'ep_formatted_args', 'filter_ep_args', 10, 2 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment