WordPress: Limit comment wordcount like Twitter

WordPress: Limit comment wordcount like Twitter

Do you like the way Twitter and some other websites show the number of words allowed in posts or comments? Twitter allows 140 characters per tweet. As you type, you can see the number of characters left to write.

You can add a wordcount limit to your comment field and restrict your visitors from writing sagas in comments.

Paste the following JavaScript in a separate file and call it comment_limiter.js or anything you like. Add it in your theme folder (anywhere you want)

    jQuery(function($) {
    // configure
    var comment_input = $( '#commentform textarea' );
    var submit_button = $( '#commentform .form-submit' );
    var comment_limit_chars = 1000;
    // stop editing here
    // display how many characters are left
    $( '<div class="comment_limit_info"><span>' + comment_limit_chars + '</span> characters left</div>' ).insertAfter( comment_input );
    comment_input.bind( 'keyup', function() {
    // calculate characters left
    var comment_length = $(this).val().length;
    var chars_left = comment_limit_chars - comment_length;
    // display characters left
    $( '.comment_limit_info span' ).html( chars_left );
    // hide submit button if too many chars were used
    if (submit_button)
    ( chars_left < 0 ) ? submit_button.hide() : submit_button.show();
    });
    });

Now when you enqueue the comment form in the functions.php or inside the head tag, remember to add comment_limiter.js and jQuery as well. You can add the following to functions.php file of the WordPress theme. I am assuming that the comment_limiter.js file has been added to the main theme folder. Take care of the PHP tags.

<?php function my_scripts() {
// Register your script location, dependencies and version
wp_register_script('comment_limiter', get_template_directory_uri() . '/comment_limiter.js', array('jquery'), '1.0' );
// Enqueue the script
wp_enqueue_script('comment_limiter');
}
add_action('wp_enqueue_scripts', 'my_scripts');
?>

This snippet automatically inserts a DIV tag below the text field and updates the character count when the user types. The submit_button is optional. Set the var to null if you don’t want it to be grayed out.

Source: WP Engineer