NB: Make sure you do a back up of your theme, files and database before attempting the tutorials

WordPress Query: Display Post Type Results from Two Date Field

---- Last modified : Oct 01 2022

Estimated reading time : 1 minute, 38 seconds - 172 words

With this tutorial, we want to return Post Type results with two date fields. In order to do so, we first need to create a Post Type. For our example, we already have a promotions Post Type. Within this Post Type, we’ve added a metabox with Two date type fields.

Both Date type fields will contain the Date field (Metakey) for the event start date and end date. Here are both field IDs:start-date-promotion and end-date-promotion.

With our Post Type and both fields with a specific date added, we need to initialize today’s date before our arguments so we can compare our meta query with the today’s date.

Display Post Type Results with Two Date Fields.

(For our example, we display on-going promotions.)

<?php // WP_Query arguments
$today = date('Y-m-d');
$args = array(
  'post_type'         => array( 'promotions' ),
  'meta_query'        => array(
	'key'		=> 'date-debut-promotion',
	'compare'	=> '<=',
	'value'		=> $today,
	'key'		=> 'date-fin-promotion',
	'compare'	=> '>=',
	'value'		=> $today,
// The Query
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) { 
// Afficher votre loop ici
<?php } } else { ?>
<?php } ?>	
<?php wp_reset_postdata(); ?>

So we have created a variable that stores today’s day and then we create our query and finally we assign a meta query or a date field start-date-promotion that needs to be lower or equal to today’s date and that the end-date-promotion is greater or equal than today’s date.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>