Custom Post Type Query for date ordering by custom field

I have an ‘events’ custom post type created with a custom field for ‘start_date’ - is there a way to order the posts in the archive template by that start_date, possibly via a controller method, and passing the fields to template via blade?

Thanks in advance.

Sure is! What have you tried so far?

Hi fabianwurk, I made it just last day.

You can try :

In app/actions.php => New file created, add it in functions.php ~ line 51
Change “timeline” by your custom post type

<?php

namespace App;

/**
 * Filter archive Timeline by ACF field event_date
 */

add_action('pre_get_posts', function ($query) {

    // do not modify queries in the admin
    if( is_admin() ) {
        return $query;
    }

    // only modify queries for 'timeline' post type
    if( isset($query->query_vars['post_type']) && $query->query_vars['post_type'] == 'timeline' ) {

        $query->set('orderby', 'meta_value');
        $query->set('meta_key', 'event_date');
        $query->set('order', 'DESC');

    }

    // return
    return $query;

});

This function “filter” WP_Query and modify the orderby param on the archive page of the cpt timeline.

3 Likes

Thanks Benoi - I’ll give that a try.