IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    WordPress 阻止非中文评论提交

    绪风发表于 2025-05-22 02:01:55
    love 0

    添加代码后,需要进行测试,防止不生效,或者与现有代码、插件冲突。

    if (!function_exists('block_non_chinese_comments_on_submit')) {
        /**
         * 阻止不包含中文的评论提交
         * @param $comment_id
         * @return void
         */
        function block_non_chinese_comments_on_submit($commentdata)
        {
            // 确保评论内容存在且不为空
            if (empty($commentdata['comment_content'])) {
                wp_die(new WP_Error('comment_empty', '<strong>错误:</strong>评论内容不能为空。<br/><br/><a href="javascript:history.back()"">« 返回</a>', 200));
            }
            $comment_content = $commentdata['comment_content'];
            // 检查评论内容是否包含中文字符
            // [\p{Han}] 匹配任何 Unicode 编码的汉字字符
            // /u 是 Unicode 模式修饰符,确保正确处理 UTF-8 字符串
            if (!preg_match("/[\p{Han}]/u", $comment_content)) {
                // 如果不包含中文字符,返回一个 WP_Error 对象
                wp_die(new WP_Error('no_chinese_chars', '<strong>错误:</strong>评论内容必须包含中文。<br/><br/><a href="javascript:history.back()"">« 返回</a>', 200));
            }
            // 如果通过验证,返回原始评论数据,允许评论提交
            return $commentdata;
        }
    
        add_filter('preprocess_comment', 'block_non_chinese_comments_on_submit');
    }

    The post WordPress 阻止非中文评论提交 appeared first on 时光散记.



沪ICP备19023445号-2号
友情链接