Only display posts after current date

The question:

All my posts have a custom field named date-start-custom. The value of the custom field is in the date format YYYY-MM-DD HH:MM (e.g: 2021-06-15 14:30), and I want to only list posts that has a date later than the current date.

I am already altering the query to sort the posts from earliest to latest, and I was hoping I could do this in the same query.

This is what my code currently looks like:

add_action( 'pre_get_posts', 'filter_posts' );
function filter_posts( $query ) {
    if( is_category() && !is_admin() && $query->is_main_query() ) {
        $query->set( 'posts_per_page','10' );
        $query->set( 'orderby','meta_value_num' );
        $query->set( 'meta_key','date-start-custom' );
        $query->set( 'order','ASC' );
    }
    return $query;
}

I googled this earlier and found this question with an answer, but it didn’t really work for me. This is the code I tried, which didn’t work:

add_action( 'pre_get_posts', 'filter_posts' );
function filter_posts( $query ) {
    $now = date("Y-m-d H:i");
    if( is_category() && !is_admin() && $query->is_main_query() ) {
        $query->set( 'posts_per_page','10' );
        $query->set( 'orderby','meta_value_num' );
        $query->set( 'meta_key','date-start-custom' );
        $query->set( 'meta_value', $now );
        $query->set( 'meta_type','DATE' );
        $query->set( 'meta_compare','>=' );
        $query->set( 'order','ASC' );
    }
     return $query;
}

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

Turns out meta_query was the way to go. This is the code I used to make it work.

add_action( 'pre_get_posts', 'filter_posts' );
function filter_posts( $query ) {
    $now = date("Y-m-d H:i", strtotime('+2 hours'));
    if( is_category() && !is_admin() && $query->is_main_query() ) {
        $query->set( 'posts_per_page','10' );
        $query->set( 'orderby','meta_value_num' );
        $query->set( 'meta_key','date-start-custom' );
        $query->set( 'meta_query', array(
            array(
                'key' => 'date-start-custom',
                'compare' => '>=',
                'value' => $now,
                'type' => 'DATE'
            )
        ));
        $query->set( 'order','ASC' );
    }
     return $query;
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment