Meta_query compare operator explanation

Meta_query compare operator explanation
=
!=
>
>=
<
<=
LIKE
NOT LIKE
IN
NOT IN
BETWEEN
NOT BETWEEN
NOT EXISTS

++++++++++++++++++++++++++++++++++

The first several work about like you would expect:

=   equals 
!=  does not equal 
>   greater than 
>=  greater than or equal to 
<   less than 
<=  less than or equal to

LIKE and NOT LIKE are SQL operators that let you add in wild-card symbols, so you could have a meta query that looks like this:

array( 
    'key' => 'name', 
    'value' => 'Pat', 
    'compare' => 'LIKE'
)

This would return all posts where the meta value “name” has the string “Pat”. In this case, “Pat” “Patricia” and “Patrick” would all be returned back to you.

Adding the wildcard character % isn’t necessary, because it gets added by default like @Herb said in his below Like this: $meta_value = '%' . like_escape( $meta_value ) . '%';

IN and NOT IN select any matches that are in (or not in) the given array. So you could do something like this:

array(
    'key'     => 'color', 
    'value'   => array('red', 'green', 'blue') 
    'compare' => 'IN'
)

and it would get all posts that have the color set to either red, green, or blue. Using ‘NOT IN’ gets the reverse, any posts that have a value set to anything else than what’s in the array.

The generated SQL for this would look something like this:

SELECT * FROM posts_meta WHERE value IN ("red", "green", "blue") 

BETWEEN and NOT BETWEEN allow you to define a range of values that could be correct, and require you to give two values in an array in your meta_query:

array( 
    'key' => 'price', 
    'value' => array(20,30) 
    'compare' => 'BETWEEN'
)

NOT EXISTS is just like what it sounds – the meta value isn’t set or is set to a null value. All you need for that query is the key and comparison operator:

array( 
    'key' => 'price', 
    'compare' => 'NOT EXISTS'
)

Hope this helps!


Jayesh Patel
Author
Jayesh Patel

Jayesh Patel is a Professional Web Developer & Designer and the Founder of InCreativeWeb.

As a highly Creative Web/Graphic/UI Designer - Front End / PHP / WordPress / Shopify Developer, with 14+ years of experience, he also provide complete solution from SEO to Digital Marketing. The passion he has for his work, his dedication, and ability to make quick, decisive decisions set him apart from the rest.

His first priority is to create a website with Complete SEO + Speed Up + WordPress Security Code of standards.



Explore

Related Articles

16th December, 2024

The WordPress Admin Dashboard: What is it and its Importance

27th November, 2024

How AI-generated Content and Plagiarism Can Be Identified?

25th November, 2024

The Advantages of Using Independent UX Designers for Your Project