Having trouble with custom date field for CPT query (WordPress)

I’ve read as many of the questions and answers on here as I can find and none of the solutions are working for me. No idea what I’m doing wrong here.

I have a CPT ‘event’ with meta key ‘start_date’ – This saves to DB in YYYY-MM-DD HH:MM:SS format exactly the same as the standard post_date format.

Yet I have a query which is not sorting these posts by the meta key but by the post_date no matter what I try.

I’ve got the actual CPT archive sorting correctly by start_date, but the query I’m using elsewhere (on homepage section) just will not work.

Here’s my query:

$the_query = new WP_Query( array(
    'post_type' => 'event',
    'posts_per_page' => 2,
    'order_by' => 'meta_value',
    'meta_key' => 'start_date'
) );
if ( $the_query->have_posts() ) {
    while ( $the_query->have_posts() ) {
        $the_query->the_post();

I’ve tried so many variations and yet it still just displays the posts by post_date rather than start_date.

Any idea what I’m doing wrong here?

Thanks

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

I’m guessing it’s because you used order_by when it should actually be orderby – that order_by wasn’t just a typo in the question, right?

And also, if the meta value is a date, then you should also set the meta_type parameter to DATE so that the sorting works as expected.

So try with:

$the_query = new WP_Query( array(
    'post_type'      => 'event',
    'posts_per_page' => 2,
    'orderby'        => 'meta_value', // it's orderby; not order_by
    'meta_key'       => 'start_date',
    'meta_type'      => 'DATE',       // and set meta_type to DATE
) );

Update

If the above still doesn’t work, try using meta_query instead of those meta_key and meta_type, and set the orderby to start_date – the key in the meta_query for the metadata start_date:

$the_query = new WP_Query( array(
    'post_type'      => 'event',
    'posts_per_page' => 2,
    'meta_query'     => array(
        'start_date' => array(
            'key'  => 'start_date',
            'type' => 'DATE',
        ),
    ),
    'orderby'        => 'start_date',
) );

However, if there’s a plugin or custom code overriding the orderby, e.g. via pre_get_posts, then I doubt the above would work.

But you can try it, who knows it magically works… also, try clearing your site caches – just in case.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply