WordPress强化-为评论功能增加字数长度限制

这个功能其实实现起来很简单,只要利用好 WordPress 为我们提供的 preprocess_comment 钩子即可,使用这个钩子可以实现对评论内容的各种处理,不管是过滤评论中的恶意链接还是处理特定的垃圾评论,通过 preprocess_comment 钩子我们都可以实现。

将下面的代码添加到当前 WordPress 主题的 functions.php 文件:

function lxtx_set_comments_length($commentdata) {
	$minCommentlength = 5; //最少字數限制,建议设置为 5-10 个字
	$maxCommentlength = 220; //最多字數限制,建议设置为 150-200 个字
	$pointCommentlength = mb_strlen($commentdata['comment_content'],'UTF8'); //mb_strlen 一个中文字符当做一个长度
	if ( ($pointCommentlength < $minCommentlength) && !is_user_logged_in() ){
	err('抱歉,您的评论字数过少,最少输入' . $minCommentlength .'个字(目前字数:'. $pointCommentlength .')【登录后无此限制】');
	exit;
	}
	if ( ($pointCommentlength > $maxCommentlength) && !is_user_logged_in() ){
	err('抱歉,您的评论字数过多,最多输入' . $maxCommentlength .'个字(目前字数:'. $pointCommentlength .')【登录后无此限制】');
	exit;
	}
	return $commentdata;
}
add_filter('preprocess_comment', 'lxtx_set_comments_length');

相关文章