1

I would like to change the sort order of a query, based on meta in the returned posts. Specifically, posts are events with an event date and I filter them as either future or past. If all events are in the past, I want the most recent ones first, if all in the future, the next to happen needs to be first. I've tried all sorts in a pre-get-posts function like:

function resort($query){
    if($query->is_main_query() && is_tax('event-category'){
        if($query->have_posts()){
            // do something based on the first post
            wp_reset_query();
        }
    }
}

The function is in functions.php and is firing but it doesn't get past have_posts(), even though the main query is returning lots of posts. What am I missing?

  1. What is it that triggers the query, and can't it be triggered anywhere? I tried query_posts() and failed.
  2. How can I construct a custom query which is exactly the main query?
  3. expense doesn't bother me - it's a small site.
  • Your conditional will never be triggered. The query has not been run yet, so you can't check if it has any posts or not. I would use a custom query in my template files instead, since what you want is going to be expensive. – Jack Johansson Aug 8 '17 at 20:20
1

Finally got it. This code in functions.php:

function set_order_by_last_date($query){

$query->set( 'orderby', 'eventstart');
$query->set( 'order', 'DESC' );
$query->get_posts();
if ($query->have_posts()){
    if ( eo_get_the_end('Ymd',$query->posts[0]->ID,$query->posts[0]->occurrence_id) > date('Ymd') ){
        $query->set( 'event_end_after', 'today' );
        $query->set( 'orderby', 'eventstart');
        $query->set( 'order', 'ASC' );
    } else {
        $query->set( 'event_end_before', 'today' );
        $query->set( 'orderby', 'eventstart');
        $query->set( 'order', 'DESC' );
    }
}
return $query->query_vars;
}

Called from the template file with:

<?php query_posts(set_order_by_last_date(clone $wp_query));?>

The vars and eo_ functions are from the excellent event organiser plug-in. Thanks @jack-johansson for the pointers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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