Support

Account

Home Forums Front-end Issues Crazy complex Query with sorting and filtering. Totally stumped.

Solved

Crazy complex Query with sorting and filtering. Totally stumped.

  • I have an Event post type with 2 fields (that matter for this), start_date (Date saved as Unix timestamp) and same_date_sort (Number).

    I need to query for events with a start_date greater than today’s date. I also need to order them by start_date AND same_date_sort, so that if 2 events have the same start date, they’ll be in the same_date_sort order.

    I’ve been writing WP_Querys and get_posts stuff for hours now and I’m stumped. Can you help me?

  • Ahh, fantastic! WP need to update their docs I see. Thanks!

  • Here’s what I ended up with, and it seems to work.

    
    $upcoming_query = new WP_Query(array(
    	'post_type'		=> 'my_event',
    	'numberposts'		=> -1,
    	'posts_per_page'	=> 1000000,
    
    	'meta_query' => array(
    		'relation' => 'AND',
    		'start_date_clause' => array(
    			'key' 		=> 'start_date',
    			'value' 	=> Carbon::now()->format("Ymd"),
    			'compare' 	=> '>=',
    		),
    		'same_date_sort_clause' => array(
    			'key' => 'same_date_sort', // higher number is earlier
    			'compare' => 'EXISTS',
    		), 
    	),
    
    	'orderby' => array(
    		'start_date_clause' 		=> "DESC",
    		'same_date_sort_clause' 	=> "ASC"
    	)
    	
    ));
    

    The same_date_sort/EXISTS clause doesn’t do anything (they all have that field), but it lets me use same_date_sort_clause/ASC for sorting below.

Viewing 4 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic.