How To Compare Between Two Dates In A WordPress Loop

Looking to compare between two dates in a WordPress loop? All you may need is to pass these arguments into your loop’s argument array.

Looping between two dynamic dates using the WordPress post's date

To loop between two dates in WordPress, you need to pass the following arguments into your WordPress query’s loop.

For example, in a scenario where you need to loop from the first day of the current month to the last:

$args = array(
     'post_type' => 'post',
     'date_query' => array(
          'after' => date( 'Y-m-01' ),
          'before' => date( 'Y-m-01', strtotime( '1 month' ) ),
          'inclusive' => true

In the event that you need the previous month, you can replace the after and before date_query keys with the following:

'after' => date( 'Y-m-01', strtotime( '-1 month' ) ),
'before' => date( 'Y-m-01' ),

Looping between two fixed dates

In order to loop between two fixed dates, you can use the same method as above and simply replace the after and before date_query keys with fixed dates accordingly.

However, it’s important to note that you may need to use the Ymd f date format here.

Looping between dates using an ACF field

In the event that you need to compare between two dates in a specific meta field, such as an ACF field. You can replace the date_complete meta_key, using the example below.

$start = date( 'Ym01' );
$end = date( 'Ym01', strtotime( '+1 month' ) );
$args = array(
     'post_type' => 'example_post_type',
     'posts_per_page' => -1,
     'meta_key' => 'date_completed',
     'meta_value' => array( $start, $end ),
     'meta_compare' => 'BETWEEN',
     'type' => 'date'

Note, the date must be in Ymd format to compare between the two.