wp query – Order by post meta not working with pre_get_posts filter
Question
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:
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:
How can I debug this situation, to make it work as expected?
Thanks!
0
10 months
2022-08-24T05:18:53-05:00
2022-08-24T05:18:53-05:00 0 Answers
0 views
0
Leave an answer