0

I've had good luck with using multiple orderby arguments in the past, but now that I'm trying it with dates I'm wondering if there's something I'm missing.

I'm trying to order some posts by an ACF datepicker, and alternatively a text field. The datepicker will return a full date e.g. 9/30/2019 and the text field is optional if they only want to use a year e.g. 2019 as the date.

I'd like to order posts In DESC order as follows (US date format):

9/30/2019 | 2019 | 2018 | 1/20/2017 | 2/10/2017 | 2017 etc

Here is my code

$args = array(
    'post_type'      => 'project',
    'tax_query'      => array(
        array(
            'taxonomy' => 'building_type',
            'field'    => 'slug',
            'terms'    => $terms_array,
        ),
    ),
    'meta_query'     => array(
        'relation'    => 'OR',
        'date_clause' => array(
            array(
                'key'     => 'completion_date',
                'compare' => 'EXISTS',
                'type'    => 'DATE',
            ),
        ),
        'year_clause' => array(
            array(
                'key'     => 'completion_year',
                'compare' => 'EXISTS',
                'type'    => 'DATE',
            ),
        ),
    ),
    'orderby'        => array(
        'year_clause' => 'DESC',
        'date_clause' => 'DESC',
        'title'       => 'DESC',
    ),
    'posts_per_page' => - 1,
);

It doesn't seem to work, and appears to be ordering by title. Adding 'type' => 'DATE' doesn't seem to have any affect. I've tried messing around with the Dsiplay/Return formats on the ACF field as well as the general WP date settings also with no apparent effect.

Am I just missing something or should I try going about this a different way?

  • How is ACF actually storing the date? To compare dates and times, you need to have it storing a full timestamp. Dates like 9/30/2019 aren't something you can compare. – WebElaine Sep 20 '19 at 20:09
  • @WebElaine the date field is a string. If I var_dump() I get string(10) "2019/06/21" – zfors Sep 23 '19 at 13:44
  • Strings like that would take a lot of extra parsing for PHP to compare them reliably. You'll need to edit your field to store the data as a timestamp. – WebElaine Sep 23 '19 at 14:11

Your Answer

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

Browse other questions tagged or ask your own question.