Custom wordpress meta query (no result)

Problem

I am looping through custom post types (Advanced Custom Fields) in WordPress. I only want to display events with start_date equal to $newdate variable, defined in the beginning.

Read More

The start_date is in the format YYYY-MM-DD HH:mm (the same as $newdate). $newdate is set to the beginning of the day so I wouldn’t exclude events with different hours in the day and compare is set to greater than (just to test the query).

However I am not getting any results.

<?php
$newdate = date('Y-m-d 00:00');
//<-- Start the Loop. -->!
$args = array( 
        'post_type' => 'epsa_events', 
        'posts_per_page' => 5,
        'orderby' => 'meta_value',
        'order' => 'ASC',
        'meta_query' => array (
            array(
            'key' => 'start_time',
            'value'   => $newdate,
            'compare' => '>=',
            'type' => 'datetime' 
            )
        )
    );

$loop = new WP_Query( $args );

Related posts

2 comments

  1. Try this query:-

    'meta_key'   =>  'event-start-date',
    'meta_query' => array (
                array(
                'key' => 'start_time',
                'value' => date('Ymd',strtotime($newdate)),
                'compare' => '>=',
                'type' => 'date' 
                )
            )
    
  2. I guess you have some small mistakes here.

    First, if you use 'orderby' => 'meta_value' you must add a 'meta_key' => KEYVALUE to your $args where KEYVALUE is the name of the custom field you want to use for sorting. Check WP_Query documentation on Order & Orderby Parameters.

    Second, assuming your start_date field type is Date Time Picker, if you want to get all events that already started you’re using the wrong comparison operator. So assuming you also want to sort by date, your $args code should be:

    $args = array(
        'post_type'      => 'epsa_events',
        'posts_per_page' => -1,
        'orderby'        => 'meta_value',
        'order'          => 'ASC',
        'meta_key'       => 'start_time',
        'meta_type'      => 'DATETIME'
        'meta_query'     => array (
            array(
                'key'     => 'start_time',
                'compare' => '<=',
                'value'   => $newdate,
                'type'    => 'DATETIME'
            )
        )
    );
    

    Take a look at Date Time Picker documentation too.

    I hope this helps!

Comments are closed.