The WordPress comment system is designed to encourage discussion around articles, which is a good thing. But in practice, we often find comments that add no value at all, such as one-word replies like “Top” or “Like”, while some users paste in large blocks of copied text from elsewhere. None of that helps increase the value of the article. We can improve the quality of WordPress comments by limiting the number of characters allowed in each comment.
Limit comment length through the preprocess_comment filter
WordPress provides the preprocess_comment filter so we can process or validate comment content before it is added to the database. When the user clicks Submit Comment, we can check the character count. If it does not meet our requirements, we can return an error message to the user.
add_filter( 'preprocess_comment', 'wpb_preprocess_comment' );
function wpb_preprocess_comment($comment) {
if ( strlen( $comment['comment_content'] ) > 500 ) {
wp_die('抱歉,评论太长了,请不要超过500字。');
}
if ( strlen( $comment['comment_content'] ) < 20 ) {
wp_die('抱歉,评论太短了,请不要少于20个字。');
}
return $comment;
}
Many spam comments are just a simple URL posted in the hope of getting a little traffic. If we raise the minimum comment length slightly, it can also help reduce comment spam to some extent.
