Thêm số điện thoại, xóa url và chặn spam link trong commnet worpdress

Thảo luận trong 'Mã nguồn mở Wordpress' bắt đầu bởi admin, 1/9/22.

  1. admin
    Tham gia ngày:
    22/5/13
    Bài viết:
    4,884
    Đã được thích:
    1,194
    Điểm thành tích:
    113
    Giới tính:
    Nam
    Thêm số điện thoại, xóa url liên kết và chặn spam link trong commnet worpdress, nhập đúng định dạng số điện thoại mới cho lưu xuống, đụng định dạng email mới cho lưu xuống, không cho phép chèn liên kết vào khung comment wordpress.

    Spamer link trong khung bình luận của wordpress ở các web lớn rất nhiều, để hạn chế số lượng bình luận rác, chèn link vào bình luận thì các bạn làm theo hướng dẫn sau sẽ làm được: chặn thông báo khi khách chèn link vào nội dung bình luận, thêm số điện thoại vào trường comment (bắt đúng định dạng số điện thoại)

    DEMO:

    Khi khách hàng truy cập vào chỉ hiện thị khung bình luận này thôi.


    commnet-wordpress.jpg

    Khi khách hàng click vào ô Bình luận sẽ hiện thị thêm các trường số tên, sđt, email
    commnet-wordpress-2.jpg

    Thông báo khi khách nhập không đúng thông tin yêu cầu:

    thong-bao.jpg

    Bước 1:
    • Đăng nhập vào function.php của themes chèn code sau vào:
    Mã:
    /* comment */
    //Add field commnet phone vào khung comment trong bài viết
    add_filter('comment_form_default_fields', 'url_filtered');
    function url_filtered($fields)
    {
        //chỉ replace thêm vào nếu nó là bài viết tin tức
        if ( is_single() && 'post' == get_post_type() ) {
            $commenter = wp_get_current_commenter();
            unset($fields['author']);
            unset($fields['email']);
            $fields[ 'author' ] = '<p class="comment-form-author">'.
                '<input id="author" name="author" type="text" value="'. esc_attr( $commenter['comment_author'] ) .
                '" size="30" placeholder="Họ tên" tabindex="1" aria-required="true" /></p>';
            $fields[ 'email' ] = '<p class="comment-form-email">'.
                '<input id="email" name="email" type="text" value="'. esc_attr( $commenter['comment_author_email'] ) .
                '" size="30" placeholder="Email" tabindex="2" /></p>';
            $fields[ 'phone' ] = '<p class="comment-form-phone">'.
                '<input id="phone" placeholder="Số điện thoại" name="phone" aria-required="true" type="text" size="30"  tabindex="4" /></p>';
            if (isset($fields['url'])) unset($fields['url']);
        }
        return $fields;
    }
    //Lưu xuống giá trị commnet, loại bỏ html trong comment phone
    add_action( 'comment_post', 'save_comment_meta_data' );
    function save_comment_meta_data( $comment_id ) {
      if ( ( isset( $_POST['phone'] ) ) && ( $_POST['phone'] != '') )
      {
        $phone = wp_filter_nohtml_kses($_POST['phone']);
        add_comment_meta( $comment_id, 'phone', $phone );
      }
    }
    
    //Bắt sự kiện lúc ấn trả lời bình luận, chưa xử lý lưu xuống của commnet để kiểm tra các trường comment xem có phù hợp không.
    add_filter( 'preprocess_comment', 'minimal_comment_length' );
    function minimal_comment_length( $commentdata ) {
        $mnicm =30;
        if ( strlen( trim( $commentdata['comment_content'] ) ) < $mnicm){
            wp_die( 'Bình luận phải lớn hơn ' .$mnicm. ' ký tự.' );
        }
        if(current_user_can('administrator') || is_admin())
        {
            return $commentdata;
        }else {
            //kiểm tra xem có url trong bình luận hay ko
            $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
            // Check if there is a url in the text
            if(preg_match($reg_exUrl, $commentdata['comment_content'], $url)) {
                wp_die( 'Trong bài viết không được chèn liên kết.' );
            }
            $reg_exUrl2 = "/[a-z0-9\-\.]+\.(com|co\.uk|net|org|vn)/";
            if(preg_match($reg_exUrl2, $commentdata['comment_content'], $url)) {
                wp_die( 'Trong bài viết không được chèn liên kết.' );
            }
        }
        if ( !is_user_logged_in()  && is_single()) {
            //kiểm tra xem sđt có đúng hay ko
            $phone = wp_filter_nohtml_kses($_POST['phone']);
    
            if($phone !== '')
            {
                $result = preg_match( '/^(09|01|02|03|04|05|06|07|08)+([0-9]{8})$/', $phone );
                if(!$result)
                {
                    wp_die( 'Số điện thoại không đúng định dạng.' );
                }
            } else{
                wp_die( 'Vui lòng nhập SĐT' );
            }
        }
        return $commentdata;
    }
    
    //[Ap_dung_trong_Admin_quan_tri] Xem Them cot du lieu trong Edit_Comment trong quan tri admin
    add_action( 'add_meta_boxes_comment', 'extend_comment_add_meta_box' );
    function extend_comment_add_meta_box() {
        add_meta_box( 'title', __( 'Data Add Comment' ), 'extend_comment_meta_box', 'comment', 'normal', 'high' );
    }
    function extend_comment_meta_box ( $comment ) {
        $phone = get_comment_meta( $comment->comment_ID, 'phone', true );
        wp_nonce_field( 'extend_comment_update', 'extend_comment_update', false );
        ?>
        <p>
            <label for="phone"><?php _e( 'Phone' ); ?></label>
            <input type="text" name="phone" value="<?php echo esc_attr( $phone ); ?>" class="widefat" />
        </p>
    
        <?php
    }
    //[Ap_dung_trong_Admin_quan_tri] Cho phep Luu xuong database khi sua o trong Edit_Comment quan tri admin
    add_action( 'edit_comment', 'extend_comment_edit_metafields' );
    function extend_comment_edit_metafields( $comment_id ) {
        if( ! isset( $_POST['extend_comment_update'] ) || ! wp_verify_nonce( $_POST['extend_comment_update'], 'extend_comment_update' ) ) return;
    
      if ( ( isset( $_POST['phone'] ) ) && ( $_POST['phone'] != ’) ) :
      $phone = wp_filter_nohtml_kses($_POST['phone']);
      update_comment_meta( $comment_id, 'phone', $phone );
      else :
      delete_comment_meta( $comment_id, 'phone');
      endif;
    }
    //đổi thẻ tag tiêu đề commnet từ h3 sang thẻ tùy chỉnh
    add_filter( 'comment_form_defaults', 'custom_reply_title' );
    function custom_reply_title( $defaults ){
      $defaults['title_reply_before'] = '<span id="reply-title" class="h4 comment-reply-title">';
      $defaults['title_reply_after'] = '</span>';
      return $defaults;
    }
    /* comment */
    
    Bước 2:
    HTML:
    $(document).ready(function () {
        $('#comment').click(function(){
            $(".comment-form-author").css("display", "block");
            $(".comment-form-phone").css("display", "block");
            $(".comment-form-email").css("display", "block");
        });
        $('.single-post #commentform #submit').click(function(){
            var vnf_regex = /((09|03|07|08|05)+([0-9]{8})\b)/g;
            var comment = $('#comment').val();
            var author = $('#author').val();
            var mobile = $('#phone').val();
            var email = $('#email').val();
            var element = document.getElementsByName("phone"); //kiểm tra xem phoe có tồn tại không, nếu không tồn tại thì đang đăng nhập là user
            var mesrs = true;
            if(element != null)
            {
                if(mobile == '' || comment == '' || author ==''){
                    alert('Vui lòng nhập các thông tin: Nội dung bình luận, họ tên, số điện thoại!');
                    mesrs = false;
                    return false;
                }
                if($('#phone').length && mobile !=='' ){
                    if (vnf_regex.test(mobile) == false)
                    {
                        alert('Số điện thoại của bạn không đúng định dạng!');
                        mesrs = false;
                        return false;
                    }
                }
                if($('#email').length && email !== '')
                {
                    var atposition = email.indexOf("@");
                    var dotposition = email.lastIndexOf(".");
                    if (atposition < 1 || dotposition < (atposition + 2)
                            || (dotposition + 2) >= email.length) {
                        alert("Địa chỉ Email không đúng định dạng.");
                        mesrs = false;
                        return false;
                    }
                }
                if(comment !== '')
                {
                    var res = comment.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g);
                    if(res != null)
                    {
                        alert("Nội dung không được chứa liên kết.");
                        mesrs = false;
                        return false;
                    }
                }
            }
            if(mesrs == false)
            {
                return false;
            }
        });
    });
    Bước 3:
    • Chèn CSS sau vào
    HTML:
    .comment-form-author, .comment-form-email, .comment-form-phone {
        display: none
    }
     
    Cảm ơn đã xem bài:

    Thêm số điện thoại, xóa url và chặn spam link trong commnet worpdress

    Chỉnh sửa cuối: 30/1/24