Inform user about automatic comment closing time – WP Engineer

close-comments

To prevent spammers from flooding old articles with useless comments you can set WordPress to close comments after a certain number of days:

It might be surprising for some users if the comments are closed automatically so it might be a good idea to inform them about the remaining time.


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( __( '(This topic will automatically close in %s. )', 'domain' ),  human_time_diff( $expires ));
    }
}

While the code should be almost self explanatory there is an interesting function not every WordPress developer might know: human_time_diff(). This function is hidden in the .../wp-includes/formatting.php file. It is originally planned to be used in themes to provide a more “human” touch to the date/time a post was written. Since the function does not care if the date is in the past or in the future we can use it for our needs.

close comment example

Keep reading the article at WP Engineer. The article was originally written by Latz on 2014-06-26 05:00:27.

The article was hand-picked and curated for you by the Editorial Team of WP Archives.

Disclosure: Some of the links in this post are "affiliate links." This means if you click on the link and purchase the product, We may receive an affiliate commission.

Leave a Comment

Your email address will not be published. Required fields are marked *

Show Your ❤️ Love! Like Us
Scroll to Top