1

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

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;
}
1
  • I can't accept this answer yet since my account is brand new, will accept it once I'm able to
    – rikart
    Jun 15 at 13:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.