Thêm Google reCAPTCHA vào WordPress không cần plugin

Spam comment trên WordPress là một vấn đề khá bực mình, mình đã từng phải đi xóa hàng trăm comment một ngày nên hiểu cái cảm giác bị spam nó như thế nào. Do đó hôm nay mình sẽ hướng dẫn các bạn thêm Google reCAPTCHA vào phần comment của WordPress giúp loại bỏ hoàn toàn kiểu spam này.

Google reCAPTCHA tính đến thời điểm viết bài là có 3 phiên bản, phiên bản V1 hiện tại không sử dụng nữa, chỉ sử dụng phiên bản 2 và 3 cho từng mục đích

  • reCAPTCHA v2: người dùng phải thực hiện hành động để xác thực không phải robot như chọn hình ảnh, bấm xác nhận tôi không phải robot
  • reCAPTCHA v3: hệ thống sẽ sử dụng những thuật toán tự động phát hiện ra robot, người dùng không phải thao tác gì thêm

Cài đặt reCAPTCHA để lấy site key và secrect key

Các bạn vào reCAPTCHA admin https://www.google.com/recaptcha/admin , tạo trang mới và điền các tham số như hình bên dưới

Label: tên của trang mới

reCAPTCHA type: chọn v2 hoặc v3 tùy theo nhu cầu của bạn

Quảng cáo

Ủng hộ website

Domain: điền tên miền không có http hoặc www

Sau khi hoàn thành các bước trên bạn sẽ nhận được 2 key như hình bên dưới

Chỉnh sửa code WordPress

Google thực hiện xác thực theo cơ chế như sau. Khi người dùng load trang và bấm gửi Comment, Google sẽ tạo ra token và gửi đến server web php WordPress. Tại server web chúng ta sẽ gửi token đến máy chủ Google để xác thực, nếu Google bảo đó là Robot thì ta chặn lại, ngược lại nếu là người dùng thì cho qua.

Cơ chế xác thực reCAPTCHA Google

Các bạn làm theo hướng dẫn sau, sẽ có 2 phần cho phiên bản v2 và v3

Phiên bản Google reCATCHA v2

Thêm đường dẫn file js vào header

<script src="https://www.google.com/recaptcha/api.js" async defer></script>

Tiếp tục thêm đoạn sau vào file functions.php ở trong Theme của bạn, nhớ thay đổi reCAPTCHA_SITE_KEY_cua_banreCAPTCHA_SECRECT_KEY_cua_ban nhé

/** 
 * Google reCAPTCHA: Thêm nút xác nhận robot ở vị trí phía trên nút Comment
 */ 
function add_google_recaptcha($submit_field) { 
    $submit_field['submit_field'] = '<div class="g-recaptcha" data-sitekey="reCAPTCHA_SITE_KEY_cua_ban"></div>'.$submit_field['submit_field']; 
    return $submit_field; 
} 
 
if (!is_user_logged_in()) { 
    add_filter('comment_form_defaults', 'add_google_recaptcha'); 
} 
 
/** 
 * Google reCAPTCHA: Đoạn này sẽ gửi thông số lên server google và trả về kết quả
 */ 
function is_valid_captcha_response($captcha) { 
    $captcha_postdata = http_build_query( 
        array( 
            'secret' => 'reCAPTCHA_SECRECT_KEY_cua_ban', 
            'response' => $captcha, 
            'remoteip' => $_SERVER['REMOTE_ADDR'] 
        ) 
    ); 
    $captcha_opts = array( 
        'http' => array( 
            'method'  => 'POST', 
            'header'  => 'Content-type: application/x-www-form-urlencoded', 
            'content' => $captcha_postdata 
        ) 
    ); 
    $captcha_context  = stream_context_create($captcha_opts); 
    $captcha_response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify", false, $captcha_context), true); 
    if(!empty($captcha_response['success'])){ 
        return true; 
    }else{ 
        return false; 
    } 
} 
 
function verify_google_recaptcha() { 
    $recaptcha = $_POST['g-recaptcha-response']; 
    if(empty($recaptcha)){ 
        wp_die(__("<b>ERROR: </b><b>Vui lòng bấm xác nhận captcha.</b><p><a href='javascript:history.back()'>« Quay lại</a></p>")); 
    }elseif(!is_valid_captcha_response($recaptcha)){ 
        wp_die(__("<b>Phát hiện ra spam</b>")); 
    } 
} 
 
if (!is_user_logged_in()) { 
    add_action('pre_comment_on_post', 'verify_google_recaptcha'); 
}

Kiểm tra thành quả, nếu nó hiện ra là đã thành công, các bạn test kết quả comment nhé.

Phiên bản Google reCATCHA v3

Cách làm cũng tương tự, tuy nhiên sẽ không có nút bấm người dùng xác nhận

Thêm đường dẫn file js vào header, nhớ thay reCAPTCHA_SITE_KEY_cua_ban nhé

<script src="https://www.google.com/recaptcha/api.js?render=reCAPTCHA_SITE_KEY_cua_ban" async defer></script>

Tiếp tục thêm đoạn này vào file function.php trong Theme

/** 
 * Google reCAPTCHA: Thêm trường input vào form comment
 */ 
function add_google_recaptcha($submit_field) { 
    $submit_field['submit_button'] = '
<input name="submitBtn" type="button" id="submitBtn" class="%3$s" value="%4$s" />
<input type="hidden" name="g-recaptcha-response" id="g-recaptcha-response"> 

    <script> 
    document.getElementById("buttonSubmit").onclick = function onClick(e) { 
        e.preventDefault(); 
        grecaptcha.ready(function() { 
            grecaptcha.execute("YOUR_reCAPTCHA_SITE_KEY", {action: "submit"}).then(function(token) { 
                document.getElementById("g-recaptcha-response").value = token; 
                document.getElementById("commentform").submit(); 
            }); 
        }); 
    } 
    </script> 
    '; 
    return $submit_field;
} 
 
if (!is_user_logged_in()) { 
    add_filter('comment_form_defaults','add_google_recaptcha'); 
} 
  
/** 
 * Google reCAPTCHA: Đoạn này sẽ gửi thông số lên server google và trả về kết quả
 */ 
function is_valid_captcha_response($captcha) { 
    $captcha_postdata = http_build_query( 
        array( 
            'secret' => 'reCAPTCHA_SECRET_KEY_cua_ban', 
            'response' => $captcha, 
            'remoteip' => $_SERVER['REMOTE_ADDR'] 
        ) 
    ); 
    $captcha_opts = array( 
        'http' => array( 
            'method' => 'POST', 
            'header' => 'Content-type: application/x-www-form-urlencoded', 
            'content' => $captcha_postdata 
        ) 
    ); 
    $captcha_context = stream_context_create($captcha_opts); 
    $captcha_response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify", false, $captcha_context), true); 
    if($captcha_response['success'] && $captcha_response['score'] > 0.5){ 
        return true; 
    }else{ 
        return false; 
    } 
} 
 
function verify_google_recaptcha() { 
    $recaptcha = $_POST['g-recaptcha-response']; 
    if(empty($recaptcha)){ 
        wp_die(__("<p><strong>Error:</strong> Phát hiện spam!</p><p><a href='javascript:history.back()'>« Quay lại</a></p>")); 
    }elseif(!is_valid_captcha_response($recaptcha)){ 
        wp_die(__("<b>Phát hiện spam!</b>")); 
    } 
} 
 
if (!is_user_logged_in()) { 
    add_action('pre_comment_on_post', 'verify_google_recaptcha'); 
}

Sau khi thực hiện xong nếu bạn thấy biểu tượng này xuất hiện ở bên dưới cùng trang web của bạn là bạn đã thành công

Vậy là mình đã hướng dẫn cho các bạn cách để thêm Google reCATCHA vào website WordPress, do cấu trúc mỗi website khác nhau nên có thể việc thêm vào file function sẽ không đạt được kết quả như mong muốn, mong các bạn hãy tìm hiểu phương pháp, thử lại nhiều lần. Nếu có gì không hiểu hãy comment bên dưới nhé

Add Comment