I want to apply a rule to my site that filters out all blog posts that are over 2 years old.
I see some solutions that involve manually putting posts into a category and hiding the category but I want a solution that is fully automated.
Is there a way to tell WP that whenever you grab posts to apply this rule:
if( !is_admin() ) {
select posts where post date > two-years-ago-today
}
Thanks
You can use the pre_get_posts
hook to modify the main query:
add_action( 'pre_get_posts', 'filter_old_posts' );
function filter_old_posts($query){
if( !is_admin() && $query->is_main_query()){
add_filter('posts_where', $callback = function( $where=""){
$where .= " AND post_date > '" . date('Y-m-d', strtotime('-2 years')) . "'";
return $where;
});
add_filter('getarchives_where', $callback );
}
}
This will filter the main query posts to return posts newer than 2 years old.
There is also a second copy of the filter that uses getarchives_where
to filter the archive widget results.