Only display posts after current date

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;
}

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

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

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x