• I’m currently working on a site where I need to have my custom posts called “Events” separated into two loops. Each event post type has a custom field called event_date which is to be used to separate the posts. One loop displays upcoming events including the current date and beyond. The second loop displays past events where all event posts with a date before the current date are shown.

    This is my current code for the upcoming events loop:

    $today = date('n-d-Y');
        $args = array(
    		'post_type' => 'event_listing',
    		'meta_key' => 'event_date',
    		'meta_value_num' => get_field('event_date'),
    		'orderby' => 'meta_value_num',
    		'order' => 'ASC',
    		'meta_query' => array (
    						array (
    							'key' => 'event_date',
    							'value' => '$today',
    							'compare' => '>=',
    							'type' => 'NUMERIC'
    						)
    						)
    
    	);
        $loop = new WP_Query( $args );

    So far I can get both loops to display all posts correctly via their dates, but once I add the meta_query to attempt to filter out the events before the current date my posts are displayed alphabetically instead of numerically (3, 31, 9, 10, 11, 2, 23) when sorting by month.

    I’ve read some things about using a filter, but I don’t understand how that would work and I assume this can be done with just the meta query if I can compare the dates correctly as numbers rather than strings.

    I’ve also used Advanced Custom Fields 4.1.8 to create my custom field if that helps.

    Thanks in advance.

Viewing 1 replies (of 1 total)
  • You CANNOT do date compares in ‘m-d-Y’ format. To compare two items, the most significant part must come first. In this case, it is the year so your format must be ‘Y-m-d’.

    This means that either the dates stored in the Custom Field must also be in that format, or you will need to do some programming to rearrange them during the query, before the compare.

Viewing 1 replies (of 1 total)
  • The topic ‘Separating Posts via Custom Date Field’ is closed to new replies.