WordPress文章评论字数限制的方法

追格官方小助手/ 2022年06月29日/ WordPress/ 浏览 1438

WordPress文章评论字数限制,如zui多多少字,zui少多少字,这样避免了垃圾信息的注入。


在当前WordPress模板 functions.php 函数文件中添加以下代码,提示文字和字数可按需修改。


add_filter( 'preprocess_comment', 'minimal_comment_length' );
    function minimal_comment_length( $commentdata ) {
      $minimalCommentLength = 40;
      if ( strlen( trim( $commentdata['comment_content'] ) ) < $minimalCommentLength )
            {
        wp_die( '抱歉,您的评论太短,请至少输入 ' . $minimalCommentLength . ' 个字' );
            }
      return $commentdata;
    }
    /**
     * https://www.zhuige.com/news/573.html
     */
    function lxtx_set_comments_length($commentdata) {
        $minCommentlength = 100; //最少字数限制
        $maxCommentlength = 200; //最多字数限制
        $pointCommentlength = mb_strlen($commentdata['comment_content'],'UTF8'); //mb_strlen
        if ( ($pointCommentlength < $minCommentlength) && !is_user_logged_in() ){
        err('抱歉!评论最少' . $minCommentlength .'个汉字(登录无此限制)');
        exit;
        }
        if ( ($pointCommentlength > $maxCommentlength) && !is_user_logged_in() ){
        err('抱歉!评论字数过长!(字数:'. $pointCommentlength .' 登录无此限制');
        exit;
        }
        return $commentdata;
    }
    add_filter('preprocess_comment', 'lxtx_set_comments_length');


发表评论

暂无评论,抢个沙发...

客服 工单