Jean R.
Jean R.

Reputation: 544

get month from date meta query in WP_Query

I store a date type stored by ACF Pro in custom meta "event_date" and I want to filter event by months with a query. The data is stored in

I know that I need to use meta_query array like this :

$args['meta_query'] = array(
    array(
        'key' => 'event_date',
        'value' => ?,
        'compare' => '=',
        'type' => 'DATE'
    )
);

But the meta query allows to compare with a full date. How to compare if the month variable (number 1 to 12) is the same that the event_date meta month ?

Thanks

Upvotes: 0

Views: 2420

Answers (1)

Outsource WordPress
Outsource WordPress

Reputation: 3799

Assuming that you are using ACF's default date 'save format' which is 'yymmdd'. Try the following 'meta query'.

FOR MONTH:

$month = date('m'); // Change to static if not current month (should be 2 digits)
$start_date = date('Y'.$month.'01'); // First day of the month
$end_date = date('Y'.$month.'t'); // Last day of the month

$args['meta_query'] = array(
    array(
        'key' => 'event_date',
        'value' => array($start_date, $end_date),
        'compare' => 'BETWEEN',
        'type' => 'DATE'
    )
);

FOR YEAR:

$year = date('Y'); // Change to static if not current year (should be 4 digits)
$start_date = date($year.'0101'); // First day of the year
$end_date = date($year.'1231'); // Last day of the year

$args['meta_query'] = array(
    array(
        'key' => 'event_date',
        'value' => array($start_date, $end_date),
        'compare' => 'BETWEEN',
        'type' => 'DATE'
    )
);

NOTE: Instead of 'type' => 'DATE', you can use 'type' => 'NUMERIC' too.

Upvotes: 1

Related Questions