简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM