2

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

3

1 Answer 1

4

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.

9
  • This looks like what I am trying to do. But I am getting an error: Fatal error: Call to a member function is_main_query() on array.
    – rgalpin
    Commented May 26, 2017 at 17:46
  • @rgalpin Oops my bad. There was a typo in the answer. I typed $query->query->is_main_query() by mistake.
    – Johansson
    Commented May 26, 2017 at 17:48
  • Thanks! That works great on the list of posts returned on my blog main page. My list of archived posts is not seeing the filter. Is there a way to catch that WP Archived list that runs down the right panel?
    – rgalpin
    Commented May 26, 2017 at 17:51
  • @rgalpin You are welcome.Do you mean the archive widget or the archive.php page?
    – Johansson
    Commented May 26, 2017 at 17:53
  • The archive widget.
    – rgalpin
    Commented May 26, 2017 at 17:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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