Minimum and Maximum Comment Length
Rejects comments shorter than 15 characters or longer than 5,000 characters. Moderators are not limited.
Opens WPIDE on
Code
add_filter( 'preprocess_comment', function ( $commentdata ) {
$min = 15;
$max = 5000;
$type = isset( $commentdata['comment_type'] ) ? $commentdata['comment_type'] : '';
if ( ( '' !== $type && 'comment' !== $type ) || current_user_can( 'moderate_comments' ) ) {
return $commentdata;
}
$text = trim( wp_strip_all_tags( (string) $commentdata['comment_content'] ) );
$length = function_exists( 'mb_strlen' ) ? mb_strlen( $text ) : strlen( $text );
if ( $length < $min ) {
wp_die( esc_html( sprintf( 'Your comment is too short. Please write at least %d characters.', $min ) ), 'Comment too short', array( 'response' => 400, 'back_link' => true ) );
}
if ( $length > $max ) {
wp_die( esc_html( sprintf( 'Your comment is too long. Please keep it under %d characters.', $max ) ), 'Comment too long', array( 'response' => 400, 'back_link' => true ) );
}
return $commentdata;
} );
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.