Set a minimum length for WordPress comments

August 25, 2014     Nirmal    

You might often come across some comments where people put their website url in order to get a link back to their website or some comments like “Nice Post”, “Great Read”, “Thanks” etc… You might always end up in moderating these types of comments and making it spam or trash it. The main purpose of comments on a blog is about discussion and people can always thank your or appreciate you by using the social like/share.

In order to check comments before saving to database WordPress provides preprocess_comment filter. Using this preprocess_comment hook you can easily get the length of the comment which the user is trying to post and then you can restrict users by providing a certain length for the comments.

Lets checkout preprocess_comment  hook and create something similar.

add_filter( 'preprocess_comment', 'magni_comment_length' );
function magni_comment_length( $commentdata ) {
	//Set a minimum length for comments.
	$mg_commentlength = 40;
	if ( strlen( trim( $commentdata['comment_content'] ) ) < $mg_commentlength )  {
		wp_die( 'Error: Make sure your comment is at least ' . $mg_commentlength . ' characters long.' );
	return $commentdata;

So in the above example we are checking the length of submitted comment using strlen php function and then we are using wp_die function to display error if the comment length is less than the specified minimum length.


Snippets, Wordpress

Leave a Reply

Please wait...
Send a message

Sorry, we aren't online at the moment. Leave a message.

Your name
* Email
* Describe your issue
Login now

Need more help? Save time by starting your support request online.

Your name
* Email
* Describe your issue
We're online!

Help us help you better! Feel free to leave us any additional feedback.

How do you rate our support?