Custom WordPress queries for time

These queries use an ACF field named start_datetime to query today’s events, this week’s events and this month’s events. You then feed the $args variable to your new WP_Query

Today’s events

$today = date('Ymd');

$args = array(
     'post_type'      => 'events',
     'meta_key'       => 'start_datetime',
     'posts_per_page' => 18,
     'orderby'        => 'meta_value_num',
     'order'          => 'ASC',
     'meta_query'     => array(
            array(
                'key'     => 'start_datetime',
                'value'   => $today,
                'compare' => '=',
                'type'    => 'DATE'
            )
      )
);

This week’s events

$day = date('w');
$week_end = date('Ymd', strtotime('+' . (6 - $day) . ' days'));
$today = date('Ymd');

$args = array(
     'post_type'      => 'events',
     'meta_key'       => 'start_datetime',
     'posts_per_page' => 18,
     'orderby'        => 'meta_value_num',
     'order'          => 'ASC',
     'meta_query'     => array(
          'relation' => 'AND',
                array(
                     'key'     => 'start_datetime',
                     'value'   => $today,
                     'compare' => '>=',
                      'type'    => 'DATE'
            ),
                array(
                     'key'     => 'start_datetime',
                     'value'   => $week_end,
                     'compare' => '<=',
                     'type'    => 'DATE'
            )
         )
     );

This month’s events

$today = date('Y-m-d');
$end_date = date( 'Y-m-t' );

$args = array(
     'post_type'      => 'events',
     'meta_key'       => 'start_datetime',
     'posts_per_page' => 18,
     'orderby'        => 'meta_value_num',
     'order'          => 'ASC',
     'meta_query' => array(
	'relation' => 'AND',
		array(
			'key' => 'start_datetime',
			'value' => $today,
			'compare' => '>=',
		),
		array(
			'key' => 'start_datetime',
			'value' => $end_date,
			'compare' => '<=',
		),
     ),
);

Leave a Reply

Your email address will not be published.