简体   繁体   中英

Trouble with filtering posts using WP_Query & dates stored as Meta values

I am having difficulty filtering date values using WP_Query and meta values that are dates. I have a custom post type and meta values for each post, two of the meta values are dates: event_start_date and event_end_date . My front-end code is working great until I require the query to only show posts where event_start_date >= today

I have 5 custom posts that I'm testing with, event_start_date values are below (each has the meta values stored as DateTime objects in the DB which I've edited below for sake of readability) :

  1. 2012-04-03
  2. 2012-04-10
  3. 2012-04-11
  4. 2012-04-17
  5. 2017-03-29

What is currently being displayed is all posts (matching the custom post type) irrespective of the date of the post. My code below is adapted from this Codex Link on WP_Query and using the rules from this Codex Link on meta_query:

$args = array(
            'post_type'      => 'event' ,
            'posts_per_page' => $numberOfPosts, //declared variable
            'meta_key'       => 'event_start_date',
            'orderby'        => 'meta_value',
            'order'          => 'ASC',
            'meta_query' => array(
                array(
                    'key'     => 'event_start_date',
                    'value'   => '2017-01-01', //I've hard-coded this to test with
                    'compare' => '>=',
                ),
            )
        );
$listings = new WP_Query( $args );

I considered that my compare operator could be the wrong way around, so I tried "<=" when I do this I get "No listing found" error.

Edit

After implementing the helpful answer below, the problem persisted, it turns out that the meta_query doesn't like the date being stored as an object. I updated how my meta_values were stored and tested again and all works.

You need to add the type argument set to DATE to the meta_query array.

The query needs to know the type of the items to compare.

'meta_query' => array(
            array(
                'key'     => 'event_start_date',
                'value'   => '2017-01-01', //I've hard-coded this to test with
                'compare' => '>=',
                'type'    => 'DATE'
            ),
        )

You will find all details for the meta_query parameter here

Hope it works after !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM