Hide past posts in Wordpress with custom field date
I want the blog posts in Wordpress to be sorted by a date set in custom field and hidden when that date has passed. I got the sorting working but not sure how to proceed further with the hiding of the posts. Date is in 2022-01-01 format in the custom field.
add_action( 'pre_get_posts', 'wpse183601_filter_category_query' );
function wpse183601_filter_category_query( $query ) {
if( is_front_page() && !is_admin() && $query->is_main_query() ) {
$meta_query = array(
array(
'meta_key' => 'event_date',
'value' => date('Y-m-d'),
'type' => 'DATE',
'compare' => '>='
)
);
$query->set( 'orderby','meta_value' );
$query->set( 'meta_key','event_date' );
$query->set( 'order','ASC' );
}
}
Solution 1:
You need to pass the $meta_query
variable to the meta_query
param. try the below code.
add_action( 'pre_get_posts', 'wpse183601_filter_category_query' );
function wpse183601_filter_category_query( $query ) {
if( is_front_page() && !is_admin() && $query->is_main_query() ) {
$meta_query = array(
array(
'meta_key' => 'event_date',
'value' => date('Y-m-d'),
'type' => 'DATE',
'compare' => '>='
)
);
$query->set( 'orderby', 'meta_value' );
$query->set( 'meta_key', 'event_date' );
$query->set( 'order', 'ASC' );
$query->set( 'meta_query', $meta_query );
}
}