diff --git a/includes/classes/Feature/Search/Search.php b/includes/classes/Feature/Search/Search.php index d27517397..30f0422e2 100644 --- a/includes/classes/Feature/Search/Search.php +++ b/includes/classes/Feature/Search/Search.php @@ -738,7 +738,8 @@ public function enqueue_block_editor_assets() { * @param WP_Query $query WP Query object */ public function exclude_posts_from_search( $filters, $args, $query ) { - $bypass_exclusion_from_search = is_admin() || ! $query->is_search(); + $bypass_exclusion_from_search = ( is_admin() && ! wp_doing_ajax() ) || ! $query->is_search(); + /** * Filter whether the exclusion from the "exclude from search" checkbox should be applied * diff --git a/tests/php/indexables/TestPost.php b/tests/php/indexables/TestPost.php index ea3252754..e351b31b7 100644 --- a/tests/php/indexables/TestPost.php +++ b/tests/php/indexables/TestPost.php @@ -8239,6 +8239,46 @@ public function testExcludeFromSearchQuery() { $this->assertEquals( 2, $query->post_count ); } + /** + * Tests query doesn't return the post in if `ep_exclude_from_search` meta is set even in AJAX context + * + * @since 5.1.4 + * @group post + */ + public function test_exclude_from_search_query_in_ajax() { + // As we explicitly check if we are in admin context, setting it up here to be sure it mirrors the expected context + set_current_screen( 'ajax' ); + add_filter( 'wp_doing_ajax', '__return_true' ); + $this->assertTrue( is_admin() ); + $this->assertTrue( wp_doing_ajax() ); + + add_filter( 'ep_ajax_wp_query_integration', '__return_true' ); + + $this->ep_factory->post->create_many( + 2, + array( + 'post_content' => 'find me in search', + 'meta_input' => array( 'ep_exclude_from_search' => false ), + ) + ); + $this->ep_factory->post->create( + array( + 'post_content' => 'exclude from search', + 'meta_input' => array( 'ep_exclude_from_search' => true ), + ) + ); + + ElasticPress\Elasticsearch::factory()->refresh_indices(); + + $args = array( + 's' => 'search', + ); + $query = new \WP_Query( $args ); + + $this->assertTrue( $query->elasticsearch_success ); + $this->assertEquals( 2, $query->post_count ); + } + /** * Tests that post meta value should be empty when it is not set. *