wordpress使用代码来过滤和阻止垃圾评论[Wordpress教程]
![wordpress使用代码来过滤和阻止垃圾评论[Wordpress教程]-度崩网-几度崩溃 wordpress使用代码来过滤和阻止垃圾评论[Wordpress教程]-度崩网-几度崩溃](https://img.vlogforum.com/imgs/2019/12/1bd0a9c5ef6e29.jpg)
将下面代码写入主题文件夹下的functions.php文件即可
方法一:过滤内容为全英文和含有日文的垃圾评论
- /* 阻止垃圾评论 */
- function refused_spam_comments( $comment_data ) {
- $pattern = '/[一-龥]/u';
- if(!preg_match($pattern,$comment_data['comment_content'])) {
- wp_die('评编辑论必须含中文!');
- }
- return( $comment_data );
- }
- add_filter('preprocess_comment','refused_spam_comments');
方法二:反垃圾评论代码
- /* 垃圾评论拦截 */
- class anti_spam {
- function anti_spam() {
- if ( !current_user_can('level_0') ) {
- add_action('template_redirect', array($this, 'w_tb'), 1);
- add_action('init', array($this, 'gate'), 1);
- add_action('preprocess_comment', array($this, 'sink'), 1);
- }
- }
- function w_tb() {
- if ( is_singular() ) {
- ob_start(create_function('$input','return preg_replace("#textarea(.*?)name=(["'])comment(["'])(.+)/textarea>#",
- "textarea$1name=$2w$3$4/textarea>",$input);') );
- }
- }
- function gate() {
- if ( !emptyempty($_POST['w']) && emptyempty($_POST['comment']) ) {
- $_POST['comment'] = $_POST['w'];
- } else {
- $request = $_SERVER['REQUEST_URI'];
- $referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '隐瞒';
- $IP = isset($_SERVER["HTTP_X_FORWARDED_FOR"]) ? $_SERVER["HTTP_X_FORWARDED_FOR"] . ' (透过代理)' : $_SERVER["REMOTE_ADDR"];
- $way = isset($_POST['w']) ? '手动操作' : '未经评论表格';
- $spamcom = isset($_POST['comment']) ? $_POST['comment'] : null;
- $_POST['spam_confirmed'] = "请求: ". $request. "n来路: ". $referer. "nIP: ". $IP. "n方式: ". $way. "n內容: ". $spamcom. "n -- 记录成功 --";
- }
- }
- function sink( $comment ) {
- if ( !emptyempty($_POST['spam_confirmed']) ) {
- if ( in_array( $comment['comment_type'], array('pingback', 'trackback') ) ) return$comment;
- //方法一: 直接挡掉, 將 die(); 前面两斜线刪除即可.
- die();
- //方法二: 标记为 spam, 留在资料库检查是否误判.
- //add_filter('pre_comment_approved', create_function('', 'return "spam";'));
- //$comment['comment_content'] = "[ 判断这是 Spam! ]n". $_POST['spam_confirmed'];
- }
- return$comment;
- }
- }
- $anti_spam = new anti_spam();
代码后面提供了两种对付垃圾评论的办法,一种是直接阻止评论,另一种是将垃圾评论放在Wordpress评论的待审核队列中,默认的是第一种,如果你想使用第二种,请给die();加上//,然后去掉“方法二”下面代码的//符号。
方法三:过滤内容包含任意日文字符的垃圾评论
- /* 阻止日文垃圾评论 */
- function BYMT_comment_jp_post( $incoming_comment ) {
- $jpattern ='/[ぁ-ん]+|[ァ-ヴ]+/u';
- if(preg_match($jpattern, $incoming_comment['comment_content'])){
- wp_die( "禁止有日文字符的评论 You should type some Chinese word" );
- }
- return( $incoming_comment );
- }
- add_filter('preprocess_comment', 'BYMT_comment_jp_post');