How to: Disable commenting on posts older than 30 days

November 25, 2008 at 8:53 am

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!