Support

Account

Home Forums General Issues Order custom posts by date picker field by $_GET query and by post_date

Solving

Order custom posts by date picker field by $_GET query and by post_date

  • I want make $_GET filter in taxonomy archive page to sort custom posts by custom field (time picker) or by post_date. But with my code, that i have right now i can sort only by custom field. When i make url query “?orderby=post_date” it still give me custom field order.

    my code

    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'] == 'text' ) {
    		
    		// allow the url to alter the query
    		if( isset($_GET['orderby']) ) {
    			
    			$query->set('orderby',  'meta_value_num post_date');	
        		$query->set('meta_key', 'text_date');
    			$query->set('order', 'DESC'); 
    			
    			
        	} 
    		
    	}
    	
    	
    	// return
    	return $query;
    
    }
    
    add_action('pre_get_posts', 'my_pre_get_posts');
  • You can’t order by the post date and/or a meta field unless you use clauses in your meta query. See this https://make.wordpress.org/core/2015/03/30/query-improvements-in-wp-4-2-orderby-and-meta_query/

  • And how my function should looks like with this improvement?

  • Well, that’s hard to say, and I don’t know exactly by looking at what you have.

    You need to add a meta query with a clause and you need to add orderby in the format shown.

    these are just some guesses, you’ll need to test. I’d have to build an entire site to test it myself

    
    $query->set('meta_query', array(
     'date_clause' => array(
        'key' => 'text_date'
        'compare' => 'EXISTS'
      }
    ));
    
    $query->set('orderby',  array(
      'date_clause' => 'DESC',
      'post_date' => 'DESC'
    ));
    
Viewing 4 posts - 1 through 4 (of 4 total)

The topic ‘Order custom posts by date picker field by $_GET query and by post_date’ is closed to new replies.