Support » Fixing WordPress » Display upcoming events then past events

  • Hello,
    I would like to sort a list of events by first displaying upcoming events, then past events (from the least old to the oldest).

    I tried this way :

    add_action( 'pre_get_posts', 'custom_query_vars' );
    function custom_query_vars( $query ) {
    	if ( !is_admin() && $query->is_main_query()) {
    		if ( in_array ( $query->get('post_type'), array('spectacles') ) ) {
    			$query->set( 'post_status', 'publish' );
    			$today = date('Ymd');
    			$meta_query = array(
    		        'relation' => 'OR',
    		        'query_one' => array(
    		            'key' => 'date',
    		            'value' 	=> $today,
    		            'compare' 	=> '>='
    		        ), 
    		        'query_two' => array(
    		            'key' => 'date',
    		            'value' 	=> $today,
    		            'compare' 	=> '<'
    		        ),
    		        
    		    );
    			$query->set( 'meta_query', $meta_query );
    			$query->set( 'orderby', array( 'query_one' => 'ASC', 'query_two' => 'DESC' ) );
    		}
    	}
    	return $query;
    }

    But it doesn’t work 🙁

    Do you have an idea ?

    Thank you in advance !

Viewing 1 replies (of 1 total)
  • I found an equivalent in pure sql:

    ORDER  BY CASE 
                WHEN eventdate = Cast(now() AS DATE) THEN 1 
                WHEN eventdate < Cast(now() AS DATE) THEN -1 
                ELSE 0
              END DESC, 
              case when eventdate < Cast(now() AS DATE) then eventdate end desc,
              case when eventdate > Cast(now() AS DATE) then eventdate end asc

    But I don’t see how it can be adapted …

Viewing 1 replies (of 1 total)
  • You must be logged in to reply to this topic.