Showing only future posts in archive based on custom field date

I have custom posts that I am displaying in an archive page. Each custom post is an even and it has a custom field called ‘show_date’. The events are listed in the archive based on the ‘show_date’.

The problem was that I only want to show future events and i am not able to do so based on the code below.

$args = array(
    'post_type' => 'esitykset',
    'meta_key' => 'show_date',
    'orderby' => 'meta_value',
    'order' => 'ASC',
    'meta_compare' =>'>=',
    'meta_value'=>time(),
    'posts_per_page' => 20,
    'paged' => get_query_var('paged')
);

I figured it out but adding some code from the questions posted here in the past.

The new code that works is:

$current_date = date('Y-m-d'); // Get the current date in the same format as date fields normally store in db
$args = array(
    'post_type' => 'esitykset',
    'meta_key' => 'show_date',
    'orderby' => 'show_date',
    'order' => 'ASC',
    'meta_query' => array(
        array(
            'key' => 'show_date',
            'value' => $current_date,
            'compare' => '>=', //Compare $current_date with _event_start_date and show only the post with a date after or equal $current_date
            'type' => 'DATE',
        ),
    ),
    'posts_per_page' => 20,
    'paged' => get_query_var('paged')
);

1 Answer
1

The problem here is that, most probably, you store date in CF show_date in ‘YYYY-mm-dd’ format.

You have to use the same format in comparisons…

Something like this should work just fine:

$args = array(
    'post_type' => 'esitykset',
    'meta_key' => 'show_date',
    'orderby' => 'meta_value',
    'order' => 'ASC',
    'meta_compare' =>'>=',
    'meta_value' => date('Y-m-d'),
    'posts_per_page' => 20,
    'paged' => get_query_var('paged')
);

Leave a Comment