• I’ve hit a wall on a WP_Query and was hoping somebody could give me a hand.

    I’m using the Advanced Custom Fields plugin to create a Events custom post type, which includes a meta_key for when the event starts and ends. I want to query all events with an end date that has not passed yet, and sort those events chronologically. This is what I got:

    <?php
    
    	$args = array(
    	    'post_type' => 'events',
    		'post_status' => 'publish',
    		'posts_per_page' => -1,
    		'meta_query' => array(
    			array(
    				'key' => 'event_end',
    				'compare' => '>=',
    				'type' => 'DATE',
    				'value' => date('Y-m-d')
    				)
    			),
    		'meta_key' => 'event_end',
    		'orderby' => 'meta_value',
    		'order' => 'ASC'
    	);
    ?>

    No posts are returned. When I remove the meta_query section, all posts are returned and sorted correctly. The problem is somewhere in the meta_query part, but I can’t figure out what it is. The event_end dates are correctly formatted (YYYY-MM-DD).

    Any help is very appreciated.

    — Anders

Viewing 1 replies (of 1 total)
  • The problem lies in the difference in the ‘type’ and ‘value’ parameters.

    ‘type’ => ‘DATE’ converts the meta_value to a date value.
    ‘value’ => date(‘Y-m-d’) returns a string value.

    A date value is an integer and will not compare correctly with a string. Try taking out the ‘type’ so the meta_value will be compared as a string.

Viewing 1 replies (of 1 total)

The topic ‘Querying posts by date meta_key, excluding posts whose date has passed’ is closed to new replies.