X

How To Require a Minimum Comment Length in WordPress

Snippets by IsItWP

Are you looking for a way to require a minimum comment length in WordPress? This snippet will display this error message if the snippet is less than 20 characters long: “All comments must be at least 20 characters long.”

Instructions:

All you have to do is add this code to your theme’s functions.php file or in a site-specific plugin:

add_filter( 'preprocess_comment', 'minimal_comment_length' );

function minimal_comment_length( $commentdata ) {
     $minimalCommentLength = 20;

     if ( strlen( trim( $commentdata['comment_content'] ) ) < $minimalCommentLength ){
       wp_die( 'All comments must be at least ' . $minimalCommentLength . ' characters long.' );
     }

     return $commentdata;
}

This snippet was created by Paul.

Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly copy / paste code snippets in WordPress, so you don’t accidentally break your site.

If you liked this code snippet, please consider checking out our other articles on the site like: WPForms vs. Gravity Forms – Best Form Plugin Showdown.

Comments   Leave a Reply

  1. Can I add custom div style for error messages?

    1. Unfortunately not that I’m aware of. This error page is not from your template but from wordpress core. I have seen some hacks but all require hacking core files and this is not a good idea.

Add a Comment Cancel reply

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!