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.
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
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.
@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
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
thanks mate
but what are the ( 30 * 24 * 60 * 60 ) other numbers?
what they do?
@kamran
From the looks of it – compares time passed since post in seconds so 30 days * 24 hours * 60 minutes * 60 seconds.
@Yan: Thank you for your support!
@kamran: Rarst was quicker tha me
Thanks you Rarst for your explanation to kamran.
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/
It is also built-in in Wp 2.7
@Söan: Good to know, thanks for notifying me!
Great recipe, thanks
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.
@DogDay: You should use the is_404 wordpress function to avoid this problem
How do I implement this function in my functions.php theme file?.
Thanks for your support?
Trackbacks: