当我们用心撰写了文章,但评论里都是些无关痛痒的短语,就很考验博主的承受能力了,为了伤害那些没有用心评论的人,可以试试这篇wordpress教程。
- 原文参考:详情

在主题根目录下的functions.php
文件中的<?php
下添加以下代码并保存。
//控制最小评论字数
//https://www.npc.ink/17995.html
add_filter( 'preprocess_comment', 'minimal_comment_length' );
function minimal_comment_length( $commentdata ) {
$minimalCommentLength = 20;
if ( strlen( trim( $commentdata['comment_content'] ) ) < $minimalCommentLength )
{
wp_die( '您的评论字数不足 ' . $minimalCommentLength . '字,<input type="button" name="Submit" onclick="javascript:history.back(-1);" value="请返回">' );
}
return $commentdata;
}
这一段是控制评论字数的,您可以根据实际需要进行修改。
$minimalCommentLength = 20;
控制最小和最大评论字数
- 代码来源:http://www.2zzt.com/jcandcj/7394.html
在主题根目录下的functions.php
文件中的<?php
下添加以下代码并保存。
/* 設定評論字數限制開始 */
function set_comments_length($commentdata) {
$minCommentlength = 3; //最少字數限制
$maxCommentlength = 1000; //最多字數限制
$pointCommentlength = mb_strlen($commentdata['comment_content'],'UTF8'); //mb_strlen 1個中文字符當作1個長度
if ($pointCommentlength < $minCommentlength){
header("Content-type: text/html; charset=utf-8");
wp_die('抱歉,您的評論字數過少,請至少輸入' . $minCommentlength .'個字(目前字數:'. $pointCommentlength .'個字)');
exit;
}
if ($pointCommentlength > $maxCommentlength){
header("Content-type: text/html; charset=utf-8");
wp_die('對不起,您的評論字數過多,請少於' . $maxCommentlength .'個字(目前字數:'. $pointCommentlength .'個字)');
exit;
}
return $commentdata;
}
add_filter('preprocess_comment', 'set_comments_length');
/* 設定評論字數限制結束 */
实战
- 将内部变量抽离到外部,方便管理
- 添加返回按钮,避免用户误操作
add_filter('preprocess_comment', array(__CLASS__, 'set_comments_length'), 10, 3);
public static function set_comments_length($commentdata, $words_number_min, $words_number_max)
{
$words_number_min = 5;
$words_number_max= 6;
$minCommentlength = $words_number_min; //最少字數限制
$maxCommentlength = $words_number_max; //最多字數限制
$pointCommentlength = mb_strlen($commentdata['comment_content'], 'UTF8'); //mb_strlen 1個中文字符當作1個長度
if ($pointCommentlength < $minCommentlength) {
header("Content-type: text/html; charset=utf-8");
$message = '抱歉,您的评论字数过少,请至少输入' . $minCommentlength . '个字(目前字数:' . $pointCommentlength . '个字)';
$message .= '<br/><a href="#" onclick="history.back();">
<button class="button" style="margin: 1em 0;">返回</button>
</a>';
wp_die($message);
exit;
}
if ($pointCommentlength > $maxCommentlength) {
header("Content-type: text/html; charset=utf-8");
$message = '对不起,您的评论字数过多,请少于' . $maxCommentlength . '个字(目前字数:' . $pointCommentlength . '个字)';
$message .= '<br/><a href="#" onclick="history.back();">
<button class="button" style="margin: 1em 0;">返回</button>
</a>';
wp_die($message);
exit;
}
return $commentdata;
}
Ajax评论方式
不可用