Skip to content

Inform user about automatic comment closing time

    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:
    close-comments
    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 .../parts/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

    Leave a Reply

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