简体   繁体   中英

Custom registration form in wordpress

I'm wordpress newbie and I have to create custom register form in wordpress. I've heard that it's able to do with PHP and AJAX.
My code looks like this at the moment : (In template file)

jQuery(document).on( "click", '.create-account-btn', function(){

   var inputEmpty = false;
     jQuery(".input__field--yoko").not("[type=submit]").each(function () {
        if (jQuery.trim(jQuery(this).val()).length == 0) inputEmpty = true;
       });
    if (inputEmpty){
        alert('Please fill all fields in the register form');
    } else {
      $.ajax({
        type: "post",
        url: "functions.php",
        dataType: 'json',
        data: {
          action: "registerAccount",
          username: $("#account-username").val(),
          password: $("#account-password").val(),
          email: $("#billing_email").val()
        },
        success:function() {
          alert("I'm created!");
        },
        error: function() {
          alert("Oh no, error! :(");
        }
    });
  }

  return false;
});

(In functions.php file)

function registerAccount() {
  if ( isset($_REQUEST) ) {
    $username = $_REQUEST['username'];
    $password = $_REQUEST['password]';
    $email = $_REQUEST['email'];
    $user_id = wp_create_user( $username, $password, $email );

    if (is_int($user_id)) {
      $wp_user_object = new WP_User($user_id);
    }
  }
    die();
}
add_action('wp_ajax_registerAccount', 'registerAccount');

The problem is I get error function in AJAX request. Both files are in same directory, do you have any clue what can be bad in this code?

With Sagar's help i managed to make it working, so it's no longer runs error function, now it calls success function, but wordpress account is not created, help me please.

This is ajaxurl which inculde by wp_head

<?php function frontend_custom_ajaxurl() { ?>
    <script type="text/javascript">
        var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
    </script>
    <?php
  }
add_action('wp_head','frontend_custom_ajaxurl');

This is your php function can do anything and put this code in functions.php

function your_function() {
    parse_str($_POST['data'], $params);
    print_r($params)
    exit;
}
add_action('wp_ajax_your_function', 'your_function');
add_action('wp_ajax_nopriv_your_function', 'your_function');

This is JQuery.

jQuery(".create-account-btn").submit(function() {
    var data = {
        action: 'your_function', // here php function such as your_function
        data: jQuery(".create-account-btn").serialize(),
    };
    jQuery.post(ajaxurl, data, function(response) {
        ......................
    },'json');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM