Support » Plugins » Hacks » compare date between in meta_query

  • Hi,
    on my page, the user chooses a event date. This date should be between the start and end date of a event.
    How can i bring this query to work?

    add_action('pre_get_posts', 'alter_query');
    
    function alter_query($query) {
    
    	if (is_search() && $query->query_vars['post_type'] == 'event') {
    
    		if (!empty($_GET['selected_date'])) {
    
    			$arr_selected_date = explode('-', $_GET['selected_date']);
    			$selected_date = mktime(0, 0, 0, $arr_selected_date[1], $arr_selected_date[2], $arr_selected_date[0]) * 1000;
    
    			$query->set(
    				'meta_query',
    				array(
    					'relation' => 'AND',
    					array(
    						'key' => '_event-date-from',
    						'value' => $selected_date,
    						'compare' => '<='
    						),
    					array(
    						'key' => '_event-date-to',
    						'value' => $selected_date,
    						'compare' => '>='
    						)
    					)
    				);
    
    		}
    
    	}
    
    }
Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    Are your event dates stored as timestamps? It appears to be the case since you are using a timestamp value. If you use phpMyAdmin to examine post meta, the values should appear like timestamps even though the field type is actually varchar.

    If that all checks out then you just need to add 'type' => 'NUMERIC', to each key array. Without this the SQL engine tries to do string comparisons with the parameters, resulting in bizarre behavior.

Viewing 1 replies (of 1 total)
  • The topic ‘compare date between in meta_query’ is closed to new replies.