First of all, $query
object is passed by reference, you don’t need to return $query
in pre_get_posts
.
Second, is_post_type_archive( 'events' )
will work just fine, you don’t need to use query->query_vars[]
.
Corrected code will look like this:
function my_pre_get_posts( $query ) {
if( ! is_admin() && is_main_query() && is_post_type_archive( 'events' ) ) {
$query->set('orderby', 'meta_value_num');
$query->set('meta_key', 'vdatum');
$query->set('order', 'ASC');
}
}
add_action('pre_get_posts', 'my_pre_get_posts');
Third, this action will probably not work in your case as you output the links to prev and next posts differently. In pre_get_posts
you can set new arguments for the main WP_Query
, but it will not work for other functions, like get_next_post()
, get_previous_post()
, get_adjacent_post()
.
However, those functions use filter get_{$adjacent}_post_sort
, with default value of "ORDER BY p.post_date $order LIMIT 1"
. You can try using this filter in combination with get_{$adjacent}_post_join
to add your meta query.
See “Filters” sections on this page.