Do you want to limit comment length in WordPress?
A comment is an ideal way of enabling discussion around your blog posts and building a community. Your website audience can share their opinion, give feedback, and ask questions.
However, there are multiple scenarios when you don’t find comments useful and helpful. Specially one-word comments.
We are moderating comments for a decade on our websites. We found out that most people are leaving comments on websites for backlinks or spamming.
Therefore, we have set a range for the comment length for our websites. An ideal comment should be above 60 characters and below 4000 characters.
WordPress doesn’t offer a way to control the comment length. Therefore we have created code snippets that you can use to limit WordPress comment length.
Set a Range for Comment Length in WordPress
The code snippet below allows you to set minimum and maximum character limits for comments in WordPress.
/**
* Set a Range for Comment Length in WordPress
*
* @param string[] $comment
* @return string[] $comment
*/
function maverick_set_comment_length_range($comment)
{
$minimum_characters = 60;
$maximum_characters = 4000;
if (strlen($comment['comment_content']) > $maximum_characters) {
wp_die('Comment is too long. The comment must be less than ' . $maximum_characters . ' characters');
}
if (strlen($comment['comment_content']) < $minimum_characters) {
wp_die('Comment is too short. Please use at least ' . $minimum_characters . ' characters.');
}
return $comment;
}
add_filter('preprocess_comment', 'maverick_set_comment_length_range');
Set Minimum Comment Length in WordPress
Use the code snippet below if you only want to set the minimum character limit for WordPress comments.
/**
* Set Minimum Comment Length in WordPress
*
* @param string[] $comment
* @return string[] $comment
*/
function maverick_set_minumum_comment_length($comment)
{
$minimum_characters = 60;
if (strlen($comment['comment_content']) < $minimum_characters) {
wp_die('Comment is too short. Please use at least ' . $minimum_characters . ' characters.');
}
return $comment;
}
add_filter('preprocess_comment', 'maverick_set_minumum_comment_length');
Set Maximum Comment Length in WordPress
Use the code snippet below if you only want to set the maximum character limit for WordPress comments.
/**
* Set Maximum Comment Length in WordPress
*
* @param string[] $comment
* @return string[] $comment
*/
function maverick_set_maximum_comment_length($comment)
{
$maximum_characters = 4000;
if (strlen($comment['comment_content']) > $maximum_characters) {
wp_die('Comment is too long. The comment must be less than ' . $maximum_characters . ' characters');
}
return $comment;
}
add_filter('preprocess_comment', 'maverick_set_maximum_comment_length');