Support

Account

Home Forums Front-end Issues pre_get_posts – order posts by two different meta_keys (ACF select field) Reply To: pre_get_posts – order posts by two different meta_keys (ACF select field)

  • Thank you for your reply, John. I did find this post, but couldn’t figure out how to use this in pre_get_posts.

    Here’s what I have tried, but of course it doesn’t work:

    function exhibition_pre_get_posts( $query ) {
    	
    	// do not modify queries in the admin
    	if( is_admin() ) {
    		return $query;
    	}
    	
    	if( isset($query->query_vars['post_type']) && $query->query_vars['post_type'] == 'exhibition' ) {
    		$query = new WP_Query( array(
        'meta_query' => array(
            'relation' => 'AND',
            'year' => array(
                'key' => 'year',
            ),
            'month' => array(
                'key' => 'month',
                'compare' => 'EXISTS',
            ), 
        ),
        'orderby' => array(
            'year' => 'DESC',
            'month' => 'DESC',
        ) 
    ) );
    	}
    
    	// return
    	return $query;
    }
    
    add_action('pre_get_posts', 'exhibition_pre_get_posts');

    I’m sure this is a rookie mistake and a misunderstanding of the fundamentals – I’m still very much a beginner, I’m afraid!