When you use meta_query to get the results either between numbers or date, the 'compare' => 'between'
parameter or can say the BETWEEN operator plays an important role.
In the meta_query, The BETWEEN operator helps you to compare the results between the array of given meta values. The values in the array can be either numbers or date.
However, you will have to set the type of the values you pass in the array, so if you are using numbers then use 'type' => 'numeric'
and for date use 'type' => 'date'
.
- How to use meta_query to compare between price or two numbers
- How to use meta_query to compare between dates in WordPress
To compare between and not between with meta_query, you will have to pass the 'compare' => 'between'
arguments in your meta_query array. And in the same way if you are trying to compare with not between, then you can pass it like 'compare' => 'not between'
.
meta_query to compare between
Let’s say, I have a custom field or meta_key named ‘post_score’ associated with my posts and I want to get the results for all the posts which have a post score between 80 to 100. So in that case, I will use meta_query with 'compare' => 'between'
like the given below.
$args = array( 'post_type' => 'posts', 'posts_per_page' => 5, 'meta_query' => array( array( 'key' => 'post_score', 'value' => array(80 , 100), 'type' => 'numeric', 'compare' => 'between' ) ) ) $query = new WP_Query( $args ); // Rest of the loop content goes here
The above code snippet will get you all the posts with a post score between 80 to 100.
meta_query to compare not between
In the same way, let’s say you want to get all the posts, but the post score should not be between 30 to 50, so in that case you can pass those values to the array and use 'compare' => 'not between'
as shown in the below code snippet.
$args = array( 'post_type' => 'posts', 'posts_per_page' => 5, 'meta_query' => array( array( 'key' => 'post_score', 'value' => array(30 , 50), 'type' => 'numeric', 'compare' => 'not between' ) ) ) $query = new WP_Query( $args ); // Rest of the loop content goes here
The above code will get you the posts with their post score not belonging to the given range.
So this is just a basic example of how the between and not between operators work with meta_query, you can also find some other meta_query examples in the below related articles tab.