I want to change the order of a feed using pre_get_posts filter. But I want to exclude dates older than today. I see how one could do that if the date were in a meta key, but the date is in post_date. How can I check post_date to only show posts later than today? The site shows future post dates.
<?php
function feedFilter($query) {
if ($query->is_feed) {
$query->set('order','ASC');
}
return $query;
}
add_filter('pre_get_posts','feedFilter');
?>
I want to change the order of a feed using pre_get_posts filter. But I want to exclude dates older than today. I see how one could do that if the date were in a meta key, but the date is in post_date. How can I check post_date to only show posts later than today? The site shows future post dates.
<?php
function feedFilter($query) {
if ($query->is_feed) {
$query->set('order','ASC');
}
return $query;
}
add_filter('pre_get_posts','feedFilter');
?>
Share
Improve this question
edited Aug 11, 2020 at 19:46
gillespieza
1,2855 gold badges26 silver badges46 bronze badges
asked Jun 4, 2012 at 11:16
Lee OraLee Ora
11 silver badge1 bronze badge
2 Answers
Reset to default 2You can't really check post_date
in pre_get_posts
, because, well, the action fires before (pre_
...) the posts have actually been fetched (...get_posts
). :)
But, you can use $query->set()
to add date parameters to the query. This is taken from an example in the WP_Query()
Codex entry:
<?php
function wpse54142_filter_pre_get_posts( $query ) {
if ( is_feed() ) {
$today = getdate();
$query->set( 'year', $today['year'] );
$query->set( 'monthnum', $today['mon'] );
$query->set( 'day', $today['mday'] );
}
return $query;
}
add_filter( 'pre_get_posts', 'wpse54142_filter_pre_get_posts' );
?>
Here's an example using a posts_where
filter:
function wpa54142_feed_filter( $query ) {
if ( $query->is_feed ) {
$query->set( 'order', 'ASC' );
add_filter( 'posts_where', 'wpa54142_filter_where' );
}
return $query;
}
add_filter( 'pre_get_posts', 'wpa54142_feed_filter' );
function wpa54142_filter_where( $where = '' ) {
$today = date( 'Y-m-d' );
$where .= " AND post_date >= '$today'";
return $where;
}