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