4

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

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.

2
  • When i use this code the main nav will disappear.
    – Rene
    Commented Nov 14, 2016 at 11:06
  • It shouldn't. This code does not interfere with navigation, it is applied only to main query outside of admin, and only on 'events' post type archive. Probably, you have an error in your code somewhere else. Commented Nov 14, 2016 at 13:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.