Skip to content

Commit

Permalink
Support excluding posts based on taxonomy in search queries (#2843)
Browse files Browse the repository at this point in the history
  • Loading branch information
trakos authored Aug 19, 2024
1 parent 4007308 commit fdd9e55
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions wp-content/themes/pub/wporg-learn-2024/inc/query.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
add_action( 'pre_get_posts', __NAMESPACE__ . '\add_excluded_to_lesson_archive_query' );
add_action( 'pre_get_posts', __NAMESPACE__ . '\filter_search_queries_by_post_type' );
add_filter( 'request', __NAMESPACE__ . '\handle_all_level_query' );
add_filter( 'jetpack_search_es_wp_query_args', __NAMESPACE__ . '\filter_jetpack_wp_search_query', 10, 2 );
add_filter( 'jetpack_search_es_query_args', __NAMESPACE__ . '\filter_jetpack_es_search_query', 10, 2 );

/**
* Modify the query by adding meta query for language if set.
Expand Down Expand Up @@ -137,3 +139,48 @@ function handle_all_level_query( $query_vars ) {

return $query_vars;
}

/**
* Remove incorrectly applied "show" taxonomy search filter from Jetpack Search queries, if set.
*
* @see https://developer.jetpack.com/hooks/jetpack_search_es_wp_query_args/
*
* @param array $query_args The current query args, in WP_Query format.
* @param \WP_Query $query The original query object.
*/
function filter_jetpack_wp_search_query( $query_args, $query ) {
if ( isset( $query_args['terms']['show'] ) ) {
unset( $query_args['terms']['show'] );
}

return $query_args;
}

/**
* Modify the underlying ES query that is passed to the Jetpack Search endpoint to support NOT IN slug tax queries.
*
* @see https://developer.jetpack.com/hooks/jetpack_search_es_query_args/
*
* @param array $es_query_args The current query args, in WP_Query format.
* @param \WP_Query $query The original query object.
*/
function filter_jetpack_es_search_query( $es_query_args, $query ) {
$tax_query = $query->get( 'tax_query', array() );
$must_not = array();
foreach ( $tax_query as $tax_query_item ) {
if ( isset( $tax_query_item['operator'] ) && 'NOT IN' === $tax_query_item['operator'] && isset( $tax_query_item['field'] ) && 'slug' === $tax_query_item['field'] ) {
$must_not[] = array( 'terms' => array( "taxonomy.{$tax_query_item['taxonomy']}.slug" => (array) $tax_query_item['terms'] ) );
}
}
if ( empty( $must_not ) ) {
return $es_query_args;
}
$es_query_args['query'] = array(
'bool' => array(
'must' => array( $es_query_args['query'] ),
'must_not' => $must_not,
),
);

return $es_query_args;
}

0 comments on commit fdd9e55

Please sign in to comment.