Disabling comments on old posts in WordPress

Automatically disable comments on old posts in WordPressIn some cases it can be very helpful to automatically disable comments on very old posts in WordPress.
A typical usecase could be a blog focusing on content that has a very short lifetime (eg. a news site).
In this case, comments are highly relevant for a limited time, but then doesn’t make that much sense when the post reaches a specific age.
In this post you’ll learn how you can automatically disable new comments when the post reaches a certain age.

Disabling the comments

To disable the comments in WordPress, you need to go to “Apperance->Editor” and open the file “functions.php”.

In some themes the file doesn’t exist. If this is the case, you need to create the file first.

In the file functions.php, insert the following code:

<?php
function close_comments_old_posts( $posts ) {
	if ( !is_single() ) { return $posts; }
        $age= 60 * 60 * 24 * 90;
	if ( time() - strtotime( $posts[0]->post_date_gmt ) > $age ) {
		$posts[0]->comment_status = 'closed';
		$posts[0]->ping_status    = 'closed';
	}
	return $posts;
}
add_filter( 'the_posts', 'close_comments_old_posts' );
?>

This code chechs the time difference between the time the post was published, and the current time.

If the post is older than a specified value ($age) further comments and pingbacks are disabled. In this example $age is 90 days (60 seconds x 60 minutes x 24 hours x 90 days), but you can easily change $age to what is suitable for your blog.

If posts are older than the value in $age, the message: “Comments are closed” will be displayed instead of the comments form.

Share and Enjoy

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS
fold-left fold-right
About the author
Jørgen Nicolaisen has been passionately interested in everything online since 1995. His experience is based on working with small hobby projects as well as high volume websites. Jørgen is currently focused on the PHP based programming framework - Codeigniter, and WordPress naturally

One Reply to Disabling comments on old posts in WordPress

  1. TheShadow says:

    Thank you for sharing this tutorial

Comments are now closed for this article.