Support

Account

Home Forums General Issues Problem selecting post within date range

Helping

Problem selecting post within date range

  • I need to select custom posts type (events) between a date range. The below query works when I have a date range between two different dates but if I want to select posts for the same day but different times, it doesnt work.

    I have a post with the datetime in meta data: 2017-08-18 20:00:00 but the below query does not select this when $start_date_time = ‘2017-08-18 00:00:00’ and $start_date_time = ‘2017-08-18 11:59:59’.

    However the below DOES work when $start_date_time = ‘2017-08-01 00:00:00’ and $start_date_time = ‘2017-08-31 11:59:59’.

    Why is that

    $events_query = new WP_Query([
    		'post_type'      => 'events',
    		'posts_per_page' => -1,
    		'no_found_rows'  => true,		
    		'meta_query' => array(
    			    'relation'		=> 'AND',
    				array(
    			        'key'		=> 'date',
    			        'compare'	=> '>=',
    			        'value'		=> $start_date_time
    			    ),
    				array(
    					'key'		=> 'date',
    					'compare'	=> '<=',
    					'value'		=> $end_date_time
    				),
    		    ),
    	]);
  • Do you mean $start_date_time and $end_date_time instead of 2x $start_date_time ?

    If so, the first example seems to be ok.
    If start_date_time = 2017-08-18 00:00:00
    and $end_date_time = 2017-08-18 11:59:59
    then it shouldn’t get a result because 2017-08-18 20:00:00 is bigger than both dates instead of bigger than one and smaller than one.

    The second example also seems to be ok.
    If start_date_time = 2017-08-01 00:00:00
    and $end_date_time = 2017-08-31 11:59:59
    then 2017-08-18 20:00:00 is bigger than start_date_time and smaller than $end_date_time so it would show.

    I don’t see anything wrong with this right now. This would give the result as expected (or i’m missing what the issue is…).

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

The topic ‘Problem selecting post within date range’ is closed to new replies.