當我們用心撰寫了文章,但評論里都是些無關痛癢的短語,就很考驗博主的承受能力了,為了傷害那些沒有用心評論的人,可以試試這篇wordpress教程。
- 原文參考:詳情

在主題根目錄下的functions.php
文件中的<?php
下添加以下代碼并保存。
//控制最小評論字數
//http://m.kartiktrivedi.com/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評論方式
不可用