Disable Comments in Old Blog Posts via PHP

How to Disable Comments in Old Blog Posts via PHP

in Posts & pages
Google+ LinkedIn

Whilst comment spam does occur on new articles, it is more common for comments spammers to target older blog posts that have established traffic and a good search engine ranking. These articles can sometimes be years old, so you may not even notice that they have been attacked. Disable comments on such old posts will lower your comments considerably.

If you’re getting a fair bit of spam on older blog posts, you may want to disable comments, pingbacks and trackbacks on older blog posts. Because your posts are still indexed by search engines so you’ll still be getting enough traffic there, but you may not want to answer questions and clearing our tons of comment spam on posts that are obsolete.

WordPress lets you automatically disable comments on posts and pages that were published a defined number of days in the past. In my experience, a couple of months is normally a good balance between keeping comments enabled on new articles and stop spammers in their tracks.

You can use this code snippet in your theme’s functions.php to disable comment and pingbacks in old blog posts. This example snippet will close comments, pingbacks and trackbacks on all blog posts older than 100 days. You can simply set the desired number of days by changing the number “100” to whatever you would like.

// disable comments in old blog posts via php
function wcs_disable_comments_old_posts( $posts ) {
  if ( !is_single() ) { return $posts; }
  if ( time() - strtotime( $posts[0]->post_date_gmt ) > ( 100 * 24 * 60 * 60 ) ) {
    $posts[0]->comment_status = 'closed';
    $posts[0]->ping_status    = 'closed';
  }
  return $posts;
}
add_filter( 'the_posts', 'wcs_disable_comments_old_posts' );

Share the love

If you like this snippet, share it with others!

Leave a Reply

Your email address will not be published. Required fields are marked *