How to Inform Your Users When Comments Are Closing

How to Inform Your Users When Comments Are Closing

WordPress allows you to close comments after a certain number of days, but if you have visitors actively taking part in a discussion in the comments of a post, it might be a shock to them when they discover they can no longer comment.

In today’s Weekend WordPress Project, I’ll show you how to add a warning message to the bottom of your posts to alert visitors when comments are due to close.

Feature image
Let your visitors know when comments are closing on your posts.

Adding “Comments Are Closing” Message

Before we get started, we need to set comments to close. In WordPress go to Settings > Discussion and in the “Other comment settings” section, tick “Automatically close comments on articles older than” and enter the number of days you want to keep comments open for.

Set your comments to close automatically.

WordPress has a handy built-in function – human_time_diff() – for displaying relative time in a human-readable format, just like Twitter and Facebook.

For example, instead of your posts displaying, “Posted on January 23 at 10.30am,” you could display, “Posted 5 hours ago.”

We can take advantage of the human_time_diff() function to display a human-readable time in our alert message.

To add “Comments on this post will automatically close in XX”, just add the following snippet to your theme’s functions.php file:

{code type=php}
add_action( ‘comment_form_top’, ‘topic_closes_in’ );

function topic_closes_in() {
global $post;
if ($post->comment_status == ‘open’) {
$close_comments_days_old = get_option( ‘close_comments_days_old’ );
$expires = strtotime( “{$post->post_date_gmt} GMT” ) + $close_comments_days_old * DAY_IN_SECONDS;
printf( __( ‘(Comments on this post will automatically close in %s. )’, ‘domain’ ), human_time_diff( $expires ));

You posts will now display a message in the comments section that provides a countdown alerting visitors when comments will close.

Comments message
The alert message will display in the comments section of your posts.

If you would like to display a different message, simply edit line 8 in the code and add in your own message.