2

That was a very dense title.

I have a custom post type "event" which has a Date/Time picker field "event_date" thanks to the Advanced Custom Fields plugin. This Date/Time picker saves a UNIX timestamp to the database. I'm trying to use WP_Query to get all events that are today or in the future. This is the code that I have right now:

$args = Array(
    'post_type'         => 'event',
    'posts_per_page'    => -1,
    'meta_key'          => 'event_date',
    'orderby'           => 'meta_value_num',
    'order'             => 'ASC',
    'meta_query'        => array(
                'key'       => 'event_date',
                'compare'   => '>=',
                'value'     => intval(strtotime(date('Y-m-d'))),
                'type'      => 'numeric'
    ),
);

$query = new WP_Query( $args );

It's giving me all the events, past and future.

I realize that the timestamps are stored as strings in the database so 'compare' => '>=' normally wouldn't work, but what what I've read on Google and in the Codex that 'type' => 'numeric' should cast the string to an integer and allow it to be compared with my value of this morning at midnight. Unfortunately that doesn't seem to be working and I don't understand why.

7

Try an array of arrays in your meta query.

$args = Array(
    'post_type'         => 'event',
    'posts_per_page'    => -1,
    'meta_key'          => 'event_date',
    'orderby'           => 'meta_value_num',
    'order'             => 'ASC',
    'meta_query'        => array(
         array(
                'key'       => 'event_date',
                'compare'   => '>=',
                'value'     => intval(strtotime(date('Y-m-d'))),
                'type'      => 'numeric'
         )
    ),
);

$query = new WP_Query( $args );
  • Thanks a lot, this is also work for me for Unix Time. (You save my lot time) – Ajay Patel Nov 22 '14 at 11:47
  • +1 for 'meta_value_num' v.s. 'meta_value' for comparing timestamps which are stored as strings. – Drakes Jul 6 '17 at 17:53
1

woa, you saved my day with this answer, i was trying to filter posts by custom numeric field called type_price and i was trying to do it that way:

'meta_query' => array(
    array(
        'key' => 'type_price',
        'value' => array( 0, 500000 ),
        'compare' => 'BETWEEN',
        'type' => 'NUMERIC',
 )),

but it should be this way to do it ASC:

array(
   'posts_per_page' => -1, 
   'meta_key' => 'type_price', 
   'orderby'  => 'meta_value_num', 
   'order' => 'ASC', 
       'meta_query' => array(
           array(
                'key' => 'type_price',
                'value' => array( 0, 500000 ),
                'compare' => 'BETWEEN',
                'type' => 'NUMERIC',
            )
        )),

thanks a lot :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.