Skip to content
Read For Learn
Read For Learn
  • Database
    • Oracle
    • SQL
  • C
  • C++
  • Java
  • Java Script
  • jQuery
  • PHP
Read For Learn
  • Database
    • Oracle
    • SQL
  • C
  • C++
  • Java
  • Java Script
  • jQuery
  • PHP

how to use reCaptcha v3 in wordpress custom login form?

I Found the Solution Finally Myself. here you are 🙂
.
inside Fuctions.php

function karnetacom_scripts(){
    
    wp_enqueue_script('ajax-forms-js',get_template_directory_uri().'/logreg/ajax-for-forms.js',array('jquery'),false,true);
    wp_localize_script('ajax-forms-js','data',array(
        'ajax_url' =>  admin_url('admin-ajax.php'),
        'redirecturlajax' => site_url(),
        
    ));

}
add_action('wp_enqueue_scripts','karnetacom_scripts');



// ajax login form
include get_template_directory() . '/logreg/ajax-login-form-function.php'; 

login form as a template page

<?php /* Template Name: login-form-ajax */ ?>

<?php get_header(); ?>
        
        <div class="usereditprofile">
        
<?php if ( is_user_logged_in() ) { ?>
    <div class="singlepagecontent wwarningparent">
        <div class="singlewarning">
            <div class="singlewarningicon">
                <i class="fas fa-exclamation-triangle"></i>
            </div>
            <div class="singlewarningtext">
            you are logged in!!!
            </div>
        </div>
    </div>
<?php } else { ?>

        
    <div id="sh-ajax-login-wrapper" class="sh-ajax-login-wrapper">

        <div class="ajax-login-message error" style="display: none;"></div>

        <form action="<?php echo get_permalink(); ?>" name="sh-ajax-login-form" id="sh-ajax-login-form" method="post">
            <input type="text" name="usernameloginajax" id="usernameloginajax" placeholder="username or email" required>
            <input type="password" name="passwordloginajax" id="passwordloginajax" placeholder="password" required>
            <input type="checkbox" name="rememberme" id="rememberme">
            <label for="rememberme">remmeber me</label>

            <input type="hidden" name="recaptcha_response" id="recaptchaResponse">

            <input type="submit" id="sh-ajax-login-submit" value="login">

            <?php wp_nonce_field('ajax-login-form-nonce','security'); ?>

        </form>
    </div>      
        
         
    <script async src="https://www.google.com/recaptcha/api.js?render=[SITE_KEY]"></script>   
        
       
        
<?php } ?>  

        </div>
        
        
<?php get_footer(); ?> 

in ajax-for-forms.js

jQuery(document).ready(function ($) {
    
    $('#sh-ajax-login-form').on('submit',function(event){
        event.preventDefault();
        var $this  = $(this);
        var $username = $this.find('#usernameloginajax').val();
        var $password = $this.find('#passwordloginajax').val();
        var $security = $this.find('#security').val();
        var $remember = $this.find('#rememberme').prop('checked');
        
        var $message = $('.ajax-login-message');
        
        $message.slideUp(300);
        
        if( $username === "" || $password === "" ){
            $message.html('<p>please fill all fields...</p>').slideDown(300);
            return false;
        } else {
            $message.html('<p>sending...</p>').slideDown(300);
        }

            grecaptcha.ready(function () {
                grecaptcha.execute('[site key]', { action: 'ajax_login_form' }).then(function (token) {
                    var recaptchaResponse = document.getElementById('recaptchaResponse');
                    recaptchaResponse.value = token;
                    
                    // Make the Ajax call here
                    $.ajax({
                        url:data.ajax_url,
                        type:'post',
                        dataType:'json',
                        data : {
                            action:'sh_ajax_login_form',
                            username: $username,
                            password: $password,
                            remember: $remember,
                            security: $security,
                            token: token,
                        },
                        success:function(response){

                            if( response.error ){
                                $message.html('<p>'+response.message+'</p>').slideDown(300);
                            }
                            if( response.success ){
                                $message.removeClass('error').addClass('success').html('<p>'+response.message+'</p>').slideDown(300);
                                //window.location.href="http://7learn.dev/profile";
                                //window.location.href = data.redirecturlajax;
                            }

                        },
                        error: function () {}

                    });
                });
            });
    });
    
}); 

in ajax-login-form-function.php

<?php

add_action('wp_ajax_nopriv_sh_ajax_login_form','sh_ajax_login_form');
function sh_ajax_login_form(){
    
    check_ajax_referer('ajax-login-form-nonce','security',true);

    $username = sanitize_text_field($_POST['username']);
    $password = sanitize_text_field($_POST['password']);
    $rememberme = isset($_POST['rememberme']);
    
    if( empty($username)  || empty($password) ){

        $result = array(
            'error' => true,
            'message' => 'please fill all fields!!!'
        );
        wp_send_json($result);
                    
    } else {
    
        // Build POST request to get the reCAPTCHA v3 score from Google
        $recaptcha_url="https://www.google.com/recaptcha/api/siteverify";
        $recaptcha_secret="[secret key]";
        //$recaptcha_response = $_POST['recaptcha_response'];
        $recaptcha_response = sanitize_text_field($_POST['token']);
        
        // Make and decode POST request
        $recaptcha = file_get_contents($recaptcha_url . '?secret=" . $recaptcha_secret . "&response=" . $recaptcha_response);
        $recaptcha = json_decode($recaptcha);
        
        //if ($recaptcha->success == true && $recaptcha->action == "contact') {
        if ($recaptcha->success == true && $recaptcha->score >= 0.5 && $recaptcha->action == 'ajax_login_form') {
        //captacha validated successfully.
                    
                    $creds = array(
                        'user_login'    => $username,
                        'user_password' => $password,
                        'rememember'    => $rememberme
                    );
                    $login_user = wp_signon($creds,false);

                    if( is_wp_error($login_user)){

                        $result = array(
                            'error' => true,
                            'message' => 'email or username is incorrect.'
                        );
                        wp_send_json($result);

                    }

                    $result = array(
                        'success' => true,
                        'message' => 'you logged in successfully.'
                    );
                    wp_send_json($result);

        } else {
                
            //echo "Robot verification failed, please try again.";
            $result = array(
                'error' => true,
                'message' => 'Something went wrong. Please try again later'
            );
            wp_send_json($result);
                
        };
    
    };

}

God Bless You 🙂

Related Posts:

  1. WordPress AJAX Login Screen
  2. jQuery’s .on() method combined with the submit event
  3. Adding “Remember Me” in custom login
  4. wp_set_auth_cookie() doesn’t work in Ajax call
  5. Nonces and Cache
  6. How to HTML5 FormData Ajax
  7. How build a custom login/register form with error handling?
  8. Custom ReCaptcha Login
  9. admin-ajax.php doesn’t work when using POST data and Axios
  10. Contact Form 7 Custom Post Action
  11. Custom Form with Ajax
  12. ajax – why multiple calls to wp_create_nonce() return same value?
  13. Detecting post type within init action
  14. How to link WordPress heartbeat to ajax form
  15. WordPress Ajax Login without page reload
  16. Ajax form submission from admin panel
  17. WordPress Nonce Issue for Ajax Login and Logout
  18. How can I automatically login using a URL?
  19. Confused on AJAX submit form through page template
  20. Prevent page reload after ajax form submission
  21. Custom Login and Registration form in Ajax
  22. submitting form via admin-ajax.php returns 0
  23. Admin Ajax and HTML5 Formdata
  24. jQuery Ajax passing empty parameters to my function?
  25. Is it safe to manually sign a user in using AJAX?
  26. Using ajax with wordpress
  27. Using AJAX with Forms
  28. Making the wordpress login form a jQuery dropdown
  29. Why a strange discrepency between get_current_user_id() when using AJAX versus output of document.cookie?
  30. Ajax image upload with media_handle_upload and form.js
  31. Ajax post returning full html page as response
  32. Sending variable from ajax on form submit
  33. contact form ajax empty response error message
  34. Can’t trigger an AJAX function with a submit button in the dashboard
  35. Ajax login without redirect/reload
  36. Dynamically add more fields/remove last field in a form
  37. Ajaxify Form That Submits To Same Page To Display Post Data [closed]
  38. Interim-Login form on frontend
  39. Using admin-ajax prevents regular php form submission
  40. Custom Login with Ajax not working with IE
  41. Specify ABSPATH in jQuery url
  42. ajax form is returning the dreaded “[HTTP/1.1 400 Bad Request” and a zero
  43. Output multi-steps form results in same page
  44. Change default login auth
  45. Using get_theme_mod in php ajax form doesn’t work
  46. How to create a form button that executes a function?
  47. How to stop being directed to admin.php after sending request to admin-ajax.php
  48. How to display contact form 7 form in vanilla js without jquery in frontend
  49. Should wordpress nonce be placed in html form or in javascript file
  50. Add Server Side validation in Ajax mail form
  51. How to send automatic response after form submission without plugin
  52. jQuery.post returns 0
  53. Ajax login fails: script sets cookies, but is_user_logged_in() returns false
  54. Opening Modal popup on Ajax form submission
  55. Registration form AJAX check for existing username (simple version)
  56. WordPress custom ajax login not working on mobile browsers
  57. Issue developing an AJAX form with WordPress
  58. Ajax show custom post data form & script
  59. Using AJAX on Contact-form the WordPress way
  60. Error while submitting form using AJAX and php
  61. Ajax contact form returnig 0
  62. Ajax Form data is not posted back to the get_results()
  63. Using AJAX for dynamic settings pages
  64. Ajax Form seems to post, but does not return
  65. Bad Request when adding new post via ajax form
  66. WordPress REST API FormData: Form Not Submitted When No Files Attached
  67. Why is die() used at the end of function that handles an Ajax request?
  68. Making my AJAX powered WordPress Crawlable
  69. How to process ajax requests correctly using ajax plugins
  70. Login with email (WP Modal Login)
  71. Ajax Redirect role = ‘Editor’ to their Dashboard after register
  72. Force redirect not logged in user to (wp-login.php or wp-admin) for specific page
  73. WordPress Ajax Not Working ( Custom Admin page)
  74. Load JavaScript from a post that’s loading into Fancybox via ajax
  75. Gravity form Load By Ajax Cannot Submit – Error 400
  76. How to store data from multiple forms using ajax and php
  77. What is the best way to do MyAjax error and success handling?
  78. Gravity Forms closes my popup on Validation Error [closed]
  79. How to change wordpress Log In text
  80. javascript ajax and nonce
  81. How to update post with Ajax (no plugin)
  82. Including ‘wp-load.php’ after another include() generates an error
  83. Converting a working AJAX form to work with WordPress
  84. Moving from one host to another – cannot access the dashboard
  85. How to keep scripts persistent during admin-ajax process when saving widget?
  86. Very weird bug: Ajax for non-admins
  87. WordPress 403 error on form submission with Ajax
  88. How to change default username field after login
  89. I am getting Admin-ajax.php 400 Error
  90. Load oEmbed iframe within ajax call
  91. Adding pagination to Ajax Query
  92. check_admin_referer fails on new AJAX plugin uninstall with “Are you sure you want to do this?”
  93. Ajax Security regarding user priviliges and nonces
  94. How to populate data from JSON using AJAX in TypeScript? [closed]
  95. Login Form Redirection
  96. Know which script/page is being called by ajax call
  97. Trying to send AJAX data to WordPress hook
  98. Login form- no feedback
  99. How to use Ajax with WordPress
  100. Using $.ajax getting 500 error
Categories ajax Tags ajax, captcha, forms, login, wp-login-form
Protect Upload Folder Files With Ampersand Problem
how to execute different sql query in non-sanitized $wpdb->get_results function

Recommended Hostings

Cloudways: Realize Your Website's Potential With Flexible & Affordable Hosting. 24/7/365 Support, Managed Security, Automated Backups, and 24/7 Real-time Monitoring.

FastComet: Fast SSD Hosting, Free Migration, Hack-Free Security, 24/7 Super Fast Support, 45 Day Money Back Guarantee.

Recent Added Topics

  • Bug in translation system: load_theme_textdomain() returns true, files are available and accessible but the language defaults to english
  • Custom Elementor controls not appearing in the widget Advanced tab using injection hooks
  • Get the name of the template/*html file used
  • Trying to Add Paging to Single Post Page
  • Sharing media files between live and staging servers
  • How to display the description of a custom post type in the dashboard?
  • Critical error on image display
  • Copying WP data and files into new install?
  • How to determine the DirectAdmin WordPress backup date?
  • How to get list of ALL tables in the database?
© 2026 Read For Learn
  • Database
    • Oracle
    • SQL
  • algorithm
  • asp.net
  • assembly
  • binary
  • c#
  • Git
  • hex
  • HTML
  • iOS
  • language angnostic
  • math
  • matlab
  • Tips & Trick
  • Tools
  • windows
  • C
  • C++
  • Java
  • javascript
  • Python
  • R
  • Java Script
  • jQuery
  • PHP
  • WordPress