0
votes

I've built a custom beaver builder (wordpress) module. I'm fetching posts via Ajax. I need to query posts based off an ACF custom field date.

I am posting the date in ISO8601 format (eg 2013-12-01T00:00:00-05:00). Server side, I grab the start and end. I convert them into the format needed for the ACF query https://www.advancedcustomfields.com/resources/date-picker/

$start_date = date('Ymd', strtotime($_POST['start']));
$end_date = date('Ymd', strtotime($_POST['end'])); 

I run the query, and get nothing. I echo the string out, and they look correct.

If I set the date as per the example in the ACF docs - it works (code below). So I must be converting the ISOdate $_POST['start'] incorrectly. How do I convert the ISODATE so that is it something that I can use in the query?

function get_ajax_event_calendar_posts() {

    $today = date('Ymd'); // this works...

    $args = array(
        'post_type' => array('event'),
        'meta_query' => array(
            array(
                'key'           => 'start_date',
                'compare'       => '<=',
                'value'         => $today,
            ),
            array(
                'key'           => 'end_date',
                'compare'       => '>=',
                'value'         => $today,
            )
        ),
        'post_status' => array('publish'),
        'posts_per_page' => 100,
        'nopaging' => true,
        'order' => 'DESC',
        'orderby' => 'date'
    );
    // The Query
    $ajaxposts = get_posts( $args ); 
    //... etc
}

** edit ** .... the date stuff wasn't the problem. I was the problem... switched my compares round the right way and all works...

1

1 Answers

1
votes

You haven't said what format you actually need to store the data, however you did say date('Ymd') works. Either way, use the DateTime class:

<?php

$x = new DateTime('2013-12-01T00:00:00-05:00');
echo $x->format('d/m/Y H:i:s') . "\n";     // 01/12/2013 00:00:00
echo $x->format('dmY') . "\n";     // 01122013

Here are the date formats https://www.php.net/manual/en/function.date.php