wp query – Order by post meta not working with pre_get_posts filter


I have a custom post type called “events”, which have an associated meta key called “date” (the event in which the event is going to happen).

I want to alter the main query for the events archive, to order them by said meta. I’m doing:

// Alter query for Events archive (order by event date post meta)
add_action( 'pre_get_posts', 'theme\banana\alter_events_archive_query', 1 );
function alter_events_archive_query( $query ) {

    if( $query->is_main_query() && !is_admin() && is_post_type_archive( 'events' ) ) {
        $query->set( 'order', 'ASC' );
        $query->set( 'meta_key', 'date' );
        $query->set( 'orderby', 'meta_value_num' );


It doesn’t order them.

I made sure that the filter is being applied correctly, thanks to query monitor I see the expected query:

enter image description here

Also, there is data in the database. If I run:

SELECT meta_key, meta_value FROM banana_postmeta WHERE post_id IN (SELECT ID FROM banana_posts WHERE post_type="events") AND meta_key = 'date'

I get:

enter image description here

How can I debug this situation, to make it work as expected?


Alvaro Franz 10 months 2022-08-24T05:18:53-05:00 0 Answers 0 views 0

Leave an answer