Skip to content

Commit

Permalink
Apply Exclude from Search on ES Query
Browse files Browse the repository at this point in the history
  • Loading branch information
burhandodhy committed Jan 20, 2023
1 parent 3470e52 commit aa438f2
Showing 1 changed file with 18 additions and 34 deletions.
52 changes: 18 additions & 34 deletions includes/classes/Feature/Search/Search.php
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ public function search_setup() {

add_action( 'init', [ $this, 'register_meta' ], 20 );
add_action( 'enqueue_block_editor_assets', [ $this, 'enqueue_block_editor_assets' ] );
add_action( 'pre_get_posts', [ $this, 'exclude_posts_from_search' ] );
add_filter( 'ep_post_filters', [ $this, 'exclude_posts_from_search' ], 10, 3 );
add_action( 'post_submitbox_misc_actions', [ $this, 'output_exclude_from_search_setting' ] );
add_action( 'edit_post', [ $this, 'save_exclude_from_search_meta' ], 10, 2 );
}
Expand Down Expand Up @@ -707,54 +707,38 @@ public function enqueue_block_editor_assets() {
/**
* Exclude posts based on ep_exclude_from_search post meta.
*
* @param WP_Query $query WP Query
* @param array $filters Filters to be applied to the query
* @param array $args WP Query args
* @param WP_Query $query WP Query object
*/
public function exclude_posts_from_search( $query ) {
public function exclude_posts_from_search( $filters, $args, $query ) {
$bypass_exclusion_from_search = is_admin() || ! $query->is_search();
/**
* Filter whether the exclusion from the "exclude from search" checkbox should be applied
*
* @since 4.4.0
* @hook ep_bypass_exclusion_from_search
* @param {bool} $bypass_exclusion_from_search True means all posts will be returned
* @param {WP_Query} $query WP Query
* @param {bool} $bypass_exclusion_from_search True means all posts will be returned
* @param {WP_Query} $query WP Query
* @return {bool} New $bypass_exclusion_from_search value
*/
if ( apply_filters( 'ep_bypass_exclusion_from_search', $bypass_exclusion_from_search, $query ) ) {
return;
return $filters;
}

// Get any meta query that's being added before.
$meta_query = (array) $query->get( 'meta_query' );

$exclude_from_search_query = [
'relation' => 'or',
[
'key' => 'ep_exclude_from_search',
'compare' => 'NOT EXISTS',
],
[
'key' => 'ep_exclude_from_search',
'value' => '1',
'compare' => '!=',
$filters[] = [
'bool' => [
'must_not' => [
[
'terms' => [
'meta.ep_exclude_from_search.raw' => [ '1' ],
],
],
],
],
];

/**
* If the current meta query only has an `OR` clause, wrap it with an `AND`
* so the criteria here is not made "optional".
*/
if ( empty( $meta_query ) || empty( $meta_query['relation'] ) || 'and' === strtolower( $meta_query['relation'] ) ) {
$meta_query[] = $exclude_from_search_query;
} else {
$meta_query = [
'relation' => 'and',
$exclude_from_search_query,
$meta_query,
];
}

$query->set( 'meta_query', $meta_query );
return $filters;
}

/**
Expand Down

0 comments on commit aa438f2

Please sign in to comment.