Query based on custom fields start and end date

I have a custom post type called Events, with 2 custom fields, start date and end date. These fields are stored using a timestamp in the database. I want to create a custom query based on these 2 values, so i can list events that are inside the specified date/time range. This is how my code looks like:

$start_date = strtotime($_POST['start_date']);
$end_date = strtotime($_POST['end_date']);
$args = array(
    'post_type' => 'event',
    'posts_per_page' => -1,
    'orderby' => 'title',
    'order' => 'ASC',
    'meta_query'=>array(
        'relation'=>'AND',
         array(
            'key' => 'event_start_date',
            'value' => $start_date,
            'compare' => '<=',
            'type' => 'NUMERIC'
         ),
         array(
            'key' => 'event_end_date',
            'value' => $end_date,
            'compare' => '>=',
            'type' => 'NUMERIC'
         )
     )
);
$events = new WP_Query($args);      

So i’m using a simple NUMERIC meta_query, since all of my values and keys stored in a timestamp. The code looks fine for me, but somehow theres no results in this query. Here is an example:

Read More

$star_date = 1343779200
$end_date = 1412121600

And one of my event post has these values as a custom field:
event_start_date = 1375315200
event_end_date = 1377734400

So it should give me at least one result, because the start_date is smaller and the end_date is higher compared to the event_start_date and event_end_date.

Any idea whats wrong?

Related posts

2 comments

  1. I think you have used wrong comparison operators in meta query .It should be >= for ‘event_start_date’ and <= for ‘event_end_date’ .

  2. $today2 = date('Ymd');  
        $current_month = date('m');
        $current_year = date('Y');
        $today1 = $_GET['event_date'];
        //echo $xx = substr($today1,0,4);
    
        $current_month = substr($today1,-4,2);
        $current_year = substr($today1,0,4);
    
        //echo 'get-->'.$today1; 
        //$today = ($today1 == '' || NULL )? $today2 : $today1; 
    
        $args = array(
    
            'post_type' => 'aw_events',
            'posts_per_page'  => $posts_per_page,
            'paged' => $paged,
            'meta_query'   => array( 
                //'relation' => 'AND',              
                array(
                    'key'   => 'event_start_date',
                    'compare'   => '<=',
                    'value'   => $current_year.''.$current_month.'30',
    
                ),
                array(
                    'key'   => 'event_end_date',
                    'compare'   => '>=',
                    'value'   => $current_year.''.$current_month.'01',
    
                ),
            ),      
    
        );
    

Comments are closed.