WordPress Query by Custom Field with date type

I want to create a query where all posts should be displayed where the custom field “expiration_date’ is larger than the date from today.
Short form: if the expiration date of the post is reached, it should no longer displayed in the query

I tried with this snippet:

Read More
        <?php
            $today = date("Y-m-d");
            $args= array(
                'tag' => 'Pinnwand',
                'meta_query' => array(
                    'key' => 'expiration_date',
                    'type' => 'DATE',
                    'value' => $today,
                    'compare' => '>'            
                )
            );
        $my_query = new WP_Query($args); ?>

the expiration date is in the format (2014-10-04) for example.
But I tried also the format “Ymd” on both sides, change the compare type, or set the type as “NUMERIC” and nothing helps. The result is, that the post will always be displayed.

It would be great if somebody could help me!

Related posts

Leave a Reply

3 comments

  1. Okay I found the mistake!
    The correct query needs one more array(). I don’t know exactly why, but in other cases the query couldn’t work with it. So here is the code

            $args= array(
                 'tag' => 'Pinnwand',
                'meta_query' => array(
                array(
                    'key' => 'expiration',
                    'type' => 'DATE',
                    'value' => $today,
                    'compare' => '>'            
                ),
                ),         
            );          
    $my_query = new WP_Query($args); ?>
    
  2. You could do a two-query exclusion. First query finds all the posts you want to exclude, then loop through those and store the post IDs in an array, then call second query excluding them using ‘post__not_in’ with the ID array as the argument.

    I would use the $wpdb object for this because it’s very efficient.

    For reference material:
    http://codex.wordpress.org/Class_Reference/WP_Query and
    http://codex.wordpress.org/Class_Reference/wpdb

    This chunk of code SHOULD do what you’re trying to do or get you close to it, and I kept your tag part of the query in there too.

    // first query to find exclusions
    $today = date("Y-m-d");
    $exclusions = $wpdb->get_results("SELECT * FROM $wpdb->posts WHERE expiration_date < ".$today);
    if ( $exclusions ) {
    foreach ( $exclusions as $exclusion ) {
        $excludeIDs[] = $exclusion->ID;
    }
    }
    
    // second query using exclusion array
    $args= array(
        'tag' => 'Pinnwand',
        'post__not_in' => $excludeIDs,           
    );
    $my_query = new WP_Query($args);