How to: Disable commenting on posts older than 30 days

Sometimes, it can be useful to automatically disable commenting on posts older than X days. There’s no built-in function in WordPress to do that, but if you still like to do it, just read this recipe.

To enable auto comment closing, simply paste the following function on the functions.php file from your theme. If that file doesn't exists, create it.

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

You can easily change the number of days after posts can't be commented by changing 30 to X on line 3 of the close_comments() function.

Credits goes to Perishable Press for thos awesome recipe!

32 Responses

Nov 25 2008 09:09

Good snippet (as always) but bad policy. Some advocate this to fight spam but it only harms valid comments and spam couldn’t care less.

Nov 25 2008 09:41

@Rarst: It fight both spam and valid comments, since this code simply disallow commenting on any post older than 30 days old. I don’t use it personally, but thought it could be useful to some :)

Nov 25 2008 11:34

Well, I’m not too sure if I were to do this but this code is really handy. I just never put much thought into doing it yet. Great code as usual, Jean.

Yan

Nov 25 2008 12:45

thanks mate
but what are the ( 30 * 24 * 60 * 60 ) other numbers?
what they do?

Nov 25 2008 13:19

@kamran

From the looks of it – compares time passed since post in seconds so 30 days * 24 hours * 60 minutes * 60 seconds.

Nov 25 2008 14:22

@Yan: Thank you for your support!

@kamran: Rarst was quicker tha me ;) Thanks you Rarst for your explanation to kamran.

Nov 26 2008 02:43

At my old company we had several popular WP blogs and moderating comments on old posts became a real pain.

I found out that Matt wrote the Close Old Posts plugin which does the same thing (default is set to 14 days):

http://wordpress.org/extend/plugins/close-old-posts/

Nov 30 2008 10:54

It is also built-in in Wp 2.7

Nov 30 2008 11:05

@Söan: Good to know, thanks for notifying me!

Jan 01 2009 22:41

Great recipe, thanks :)

Feb 25 2009 11:32

This function works great, but it crashes my 404 error page.

If this function is active and somebody makes a search with no results, 404 page should be shown, but instead of that I get a blank page with the ‘no comments allowed to this old post’ message.

If I deactivate this function, everything works again. Im using wp 2.7.1.

Feb 25 2009 11:59

@DogDay: You should use the is_404 wordpress function to avoid this problem :)

Feb 25 2009 12:57

How do I implement this function in my functions.php theme file?.

Thanks for your support?

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required