Add Snippet To Project
If you’re a WordPress site owner who relies on comments to interact with your readers, you may have noticed that comments get automatically closed after a specific amount of time. This is a default setting in WordPress that is designed to prevent spam and maintain the quality of your site. While this feature can be helpful in keeping your website clean, it can also cause frustration for your readers who may feel like they missed their chance to engage in the conversation. In this article, we’ll discuss how to inform your users about the automatic comment closing time on your WordPress site.
function wpturbo_display_comment_closing_time() {
$close_time = date('F jS, Y h:i:s a',wp_next_scheduled('wp_close_comments'));
if( $close_time ) {
?>
<div class="notice notice-info">
<p><?php printf( __( 'Comments on this post will be automatically closed on %s.', 'wpturbo' ), $close_time ); ?></p>
</div>
<?php
}
}
add_action( 'comment_form_before', 'wpturbo_display_comment_closing_time' );
The purpose of this code snippet is to inform users of when comments will be automatically closed on a WordPress post. This is useful for site administrators who want to keep their comments section tidy by disabling comments on older posts or by creating a discussion deadline for a particular post.
The code defines a new function called wpturbo_display_comment_closing_time()
. This function is responsible for getting the date and time when comments will be closed on the WordPress post and showing a message to users.
Inside the function, we first get the closing date and time of the comments using the WordPress wp_next_scheduled()
function. This function returns the timestamp of the next scheduled comment closure, as set in the WordPress site settings. We use the PHP date()
function to format the timestamp into a readable date and time format.
Once we have the closing date and time, we check if it is not empty, and if it isn't, we display the message on the frontend of the WordPress site:
<div class="notice notice-info">
<p><?php printf( __( 'Comments on this post will be automatically closed on %s.', 'wpturbo' ), $close_time ); ?></p>
</div>
We wrap this message in a div
element with a class of notice notice-info
, which changes the appearance of the message. The printf()
function is used to output the message, using the __()
function for internationalization.
Finally, we add an action hook to the comment_form_before
action, which ensures that the message is displayed above the comment form on the frontend. That's it! You now have a custom function that informs users of when comments will be closed for a particular post.