Home > Software engineering >  Wordpress ordering posts by meta_value_date not working as expected
Wordpress ordering posts by meta_value_date not working as expected

Time:10-22

When trying to output posts ordered by a date value given as post meta, the output is not as expected, and I cannot figure out why.

$tourDates = get_posts(array(
    'post_type'     => 'tour',
    'numberposts'   => 4,
    'meta_key'      => '_sm_tour_date',
    'orderby'       => 'meta_value_date',
    'meta_type'     => 'DATE',
    'order'         => 'ASC',
    'meta_query'    => array(
        array(
            'key'       => '_sm_tour_date',
            'compare'   => '>=',
            'value'     => date('Y-m-d')
        )
    )
));

The dates for each post are being stored as YYYY-MM-DD, and this is confirmed when I add an output of each event date on the front end (Which is showing how it is outputting in the wrong order).

enter image description here

Can't actually think of anything to change though, and the docs I've gone over seem to suggest my code is correct (as is the meta_query).

I have no custom ordering plugins to change the ordering rules also.

Does anyone have any tips or ideas?

CodePudding user response:

Just a guess but try changing 'orderby' value to 'meta_value' rather than using 'meta_value_date'.

If that doesn't work, I typically have a hard time with get_posts queries that use meta_query. Did you using WP_Query instead of get_posts?

  • Related