1

I have a custom field which stores a date in a timestamp. I want to run a query that display posts based on the month, for example all entries from March, the specific day or year doesn't matter. I'm guessing i need to use the DATE or the DATETIME type for the meta query, but i don't know how to proceed:

if ($_GET['month']) {
    $meta_query[] = array(
            'key' => 'event_start_date',
            'value' => $_GET['month']
    );
}

$args = array(
    'post_type' => 'event',
    'paged' => $paged,
    'posts_per_page' => -1,
    'tax_query' => $cleanArray,
    'meta_key' => 'event_start_date',
    'orderby' => 'meta_value_num',
    'order' => 'DESC',
    'meta_query'=> $meta_query
);

$events = new WP_Query($args);
1
  • 1
    I don't think you'll be able to do this with just WP_Query, you'll need a filter on posts_where to query on just the month using MySQL's month function.
    – Milo
    Oct 14 '13 at 16:10
5

You need the 2 digit month number that you want to query on and then use the code below. This should be easy with php (for example, see this post). In the code below $month is the number of the month in a 2 digit format, eg March would be 03.

$start_date = date('Y'.$month.'01'); // First day of the month
$end_date = date('Y'.$month.'t'); // 't' gets the last day of the month

$meta_query = array(
    'key'       => 'event_start_date',
    'value'     => array($start_date, $end_date),
    'compare'   => 'BETWEEN',
    'type'      => 'DATE'
);
1
  • 1
    Wouldn't this only compare the current year for $start_date and $end_date? Nov 27 '17 at 17:36
1

For Date Time just add eg. 00:00:00 - 23:00:00

$month      = $_GET['month'];
$start_date = date( 'Y-' . $month . '-01 00:00:00' );
$end_date   = date( 'Y-' . $month . '-t 23:00:00', strtotime( $start_date ) );

$meta_query = array(
    'key'       => 'event_start_date',
    'value'     => array($start_date, $end_date),
    'compare'   => 'BETWEEN',
    'type'      => 'DATETIME'
);
-1

WordPress 3.7 introduced the date_query to display posts by month:

$args = array(
    'date_query' => array(
        array(
            'month' => $month
        )
    )
);
$query = new WP_Query( $args );
1
  • date_query is for posts's published or modified dates, not for custom dates (events, bookings, etc).
    – cybmeta
    Oct 25 '17 at 14:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.