Skip to content

Commit

Permalink
Merge pull request #2157 from 10up/feature/not-like-meta-query-issue-…
Browse files Browse the repository at this point in the history
…2015

Add support to 'NOT LIKE' operator for meta_query
  • Loading branch information
brandwaffle authored Apr 16, 2021
2 parents 1e0c684 + 6386d24 commit 3966954
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
17 changes: 16 additions & 1 deletion includes/classes/Indexable.php
Original file line number Diff line number Diff line change
Expand Up @@ -541,7 +541,7 @@ public function build_meta_query( $meta_queries ) {
$meta_key_path = 'meta.' . $single_meta_query['key'];
} elseif ( in_array( $compare, array( '=', '!=' ), true ) && ! $type ) {
$meta_key_path = 'meta.' . $single_meta_query['key'] . '.raw';
} elseif ( 'like' === $compare ) {
} elseif ( in_array( $compare, array( 'like', 'not like' ), true ) ) {
$meta_key_path = 'meta.' . $single_meta_query['key'] . '.value';
} elseif ( $type && isset( $meta_query_type_mapping[ $type ] ) ) {
// Map specific meta field types to different Elasticsearch core types
Expand Down Expand Up @@ -723,6 +723,21 @@ public function build_meta_query( $meta_queries ) {
);
}
break;
case 'not like':
if ( isset( $single_meta_query['value'] ) ) {
$terms_obj = array(
'bool' => array(
'must_not' => array(
array(
'match_phrase' => array(
$meta_key_path => $single_meta_query['value'],
),
),
),
),
);
}
break;
case '=':
default:
if ( isset( $single_meta_query['value'] ) ) {
Expand Down
30 changes: 30 additions & 0 deletions tests/php/indexables/TestPost.php
Original file line number Diff line number Diff line change
Expand Up @@ -2732,6 +2732,36 @@ public function testMetaQueryLike() {
$this->assertEquals( 3, $query->found_posts );
}

/**
* Test a query that searches and filters by a meta value using NOT LIKE operator
*
* @since 3.6.0
* @group post
*/
public function testMetaQueryNotLike() {
Functions\create_and_sync_post( array( 'post_content' => 'post content findme' ), array( 'test_key' => 'ALICE in wonderland' ) );
Functions\create_and_sync_post( array( 'post_content' => 'post content findme' ), array( 'test_key' => 'alice in melbourne' ) );
Functions\create_and_sync_post( array( 'post_content' => 'post content findme' ), array( 'test_key' => 'AlicE in america' ) );

ElasticPress\Elasticsearch::factory()->refresh_indices();
$args = array(
's' => 'findme',
'meta_query' => array(
array(
'key' => 'test_key',
'value' => 'melbourne',
'compare' => 'NOT LIKE',
),
),
);

$query = new \WP_Query( $args );

$this->assertTrue( isset( $query->posts[0]->elasticsearch ) );
$this->assertEquals( 2, $query->post_count );
$this->assertEquals( 2, $query->found_posts );
}

/**
* Test meta queries with multiple keys
*/
Expand Down

0 comments on commit 3966954

Please sign in to comment.