Site logo

Archived topic

Setting a character limit on wordpress comments

1 reply · Started by culpable on January 26, 2019

Viewing posts 1–2 of 2

Hiya,

I've noticed that a lot of spam I receive on my website just fills up the comment section with random garbage.

As such, I was looking at setting up a character limit on comments. While there are plugins that will do this for me, I'd like to stay as lean as possible for this kind task.

Before I set it live though I just wanted to check:

Using the code mentioned here: https://www.wpbeginner.com/wp-tutorials/how-to-limit-comment-length-in-wordpress/ without the minimum limit:

add_filter( 'preprocess_comment', 'wpb_preprocess_comment' );
 
function wpb_preprocess_comment($comment) {
    if ( strlen( $comment['comment_content'] ) > 3000 ) {
        wp_die('Comment is too long. Please keep your comment under 3000 characters.');
    }
    return $comment;
}

Or alternatively, the code mentioned here: https://wpeden.com/tipsntuts/set-maximum-comment-length-in-wordpress/

add_filter( 'preprocess_comment', 'limit_comment_length' );

function limit_comment_length($comment) {

    $max_length = 3000; // Set your length here
    if ( strlen( $comment['comment_content'] ) > $max_length ) {
        wp_die('Please keep your comment under '.$max_length.' characters.');
    }
    
    return $comment;
}

Adding this PHP to my site via the recommended methods, are there any issues with this?

And although both pieces of code achieve seemingly the same task – is there a preferred option (more secure, faster, etc)?

Thank you very much for your help

Hi there,

I don't see any issues with this.

You can always try both and see which one works better for you :)

I don't think you need to worry about the difference in speed.

This archived topic is closed to new replies.