How to Use meta_query to Compare Between Dates in WordPress

If you are using meta_query and want to get the results between dates then let me guide you to achieve that.

In the WordPress database, the dates are stored in the YYYY-MM-DD format, so to get the correct results it’s very important that the format of your date should match the WordPress database date format.

By saying that, means in your date format the year comes first, then month and then the day. However you are free to use any format like YYYY/MM/DD, YY/MM/DD, Y/M/D and separators like either YY-MM-DD or YY/MM/DD.

But if for some reason your date format is different then the WordPress database date format, then make sure you convert your date format and match it to the required database date format.

meta_query to Compare Between Dates in WordPress

To use meta_query to compare between dates you will have to pass the arguments 'compare' => 'between' and 'type' => 'date' to the meta_query array. Let me show you by example.

Let say, I have a custom post type Movies and I have a custom field or meta key named release_date associated with it. Now I want to get list of all the movies between given dates,


$args = array(

		'post_type' 	 => 'movies', // my custom post type	
		'post_status' 	 => 'publish',
		'posts_per_page' => '10',
		'meta_query'	 => array(

					array(

						'key'     => 'release_date',
						'value'   =>  array( '2019-01-01', '2019-12-31' ),
						'type'	  =>  'date',
						'compare' =>  'between'	

					)
				)			
	);


$query = new WP_Query($args);

// Rest of the loop content goes here

The above code will get the list of all the movies released between 2019-01-01 to 2019-12-31.

To make example simple, I just put the date value manually, however you can pass the date value dynamically as per your needs and requirements.

Owner of diveinwp.com, solely responsible for creating helpful, informative content about WordPress, a fulltime WordPress developer with 8+ years of hands-on experience in WordPress design and development.