Home / Limit Comments & Display Character Count
Duplicate Snippet

Embed Snippet on Your Site

Limit Comments & Display Character Count

Limit comment length and display a count of characters.

50+
Code Preview
php
<?php
if ( ! class_exists( 'WPCode_Comment_Limit_Counter' ) ) {
	class WPCode_Comment_Limit_Counter {
		// Update this value to change the maximum number of characters allowed in a comment.
		protected $comment_max_length = 1000;
		// Update this value to change the minimum number of characters that a comment must have to go through.
		protected $comment_min_length = 10;
		public function __construct() {
			add_action( 'comment_form', array( $this, 'add_comment_counter_markup' ) );
			add_action( 'comment_form', array( $this, 'add_comment_counter_js' ) );
			add_filter( 'preprocess_comment', array( $this, 'prevent_long_comments' ) );
		}
		public function add_comment_counter_markup() {
			?>
			<div id="comment-counter" style="margin-top: 10px;">Characters:
				<span id="comment-counter-count">0</span>/<?php echo absint( $this->comment_max_length ); ?>
			</div>
			<?php
		}
		public function add_comment_counter_js() {
			?>
			<script type="text/javascript">
				document.addEventListener( 'DOMContentLoaded', function () {
					var commentTextarea = document.getElementById( 'comment' );
					var counterDisplay = document.getElementById( 'comment-counter-count' );
					function updateCounter() {
						counterDisplay.textContent = commentTextarea.value.length;
					}
					commentTextarea.addEventListener( 'input', updateCounter );
					updateCounter();
				} );
			</script>
			<?php
		}
		public function prevent_long_comments( $comment ) {
			if ( strlen( $comment['comment_content'] ) > $this->comment_max_length ) {
				wp_die( sprintf( 'Comment is too long. Please keep your comment under %s characters.', $this->comment_max_length ) );
			}
			if ( strlen( $comment['comment_content'] ) < $this->comment_min_length ) {
				wp_die( sprintf( 'Comment is too short. Please use at least %s characters.', $this->comment_min_length ) );
			}
			return $comment;
		}
	}
}
new WPCode_Comment_Limit_Counter();

Comments

Add a Comment