Pre get posts for single post

I pre get posts for a events archive page:
http://www.netzwerk-leipziger-freiheit.de/veranstaltungen/

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

// only modify queries for 'event' post type
if( isset($query->query_vars['post_type']) && $query->query_vars['post_type'] == 'events' ) {
    $query->set('orderby', 'meta_value_num');   
    $query->set('meta_key', 'vdatum');   
    $query->set('order', 'ASC');
}

   // return
    return $query;
}

add_action('pre_get_posts', 'my_pre_get_posts');

This will all work but if you select a single event the order is not depend on the pre get post query. And when you go to the last event on the left button on an event it ends in a 404.

I will be happy for any solution.

1 Answer
1

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.

Leave a Comment