user2740557
user2740557

Reputation: 65

Wordpress Add user by javascript

I have a wordpress website en would like to create users with a button (to start with)

It works in pieces, but i can't get this two pieces to work together

i have this piece of code (works on functions.php , but not in my createaccount.php file)

 $userid = new WP_User(wp_create_user( 'My_new_name' , '123458' , '[email protected]'));
   $userid->set_role('client');  //custom role 'client' already set

this on jquery //php file works when echo 'test';

$(document).ready( function() {

   $('#newbtnaccount').click( function() {

      $.post('php/createaccount.php', { } , 
                      function(data) {

                         alert(data);

    });

  });
});  

i already tried a lot of options but nothings seems to work yet.

Anyone who can Help? Thanks!

Upvotes: 1

Views: 1913

Answers (1)

vard
vard

Reputation: 4136

In wordpress you can make an AJAX request to admin-ajax.php and attach functions in your functions.php file with wp_ajax_my_action (for logged users) and wp_ajax_nopriv_my_action (for non logged users).

1. Set the admin-ajax.php url available as JS variable

In header.php add this in the head part:

<script type="text/javascript">
var ajax_url = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>

2. Request the function through ajax

You need to add an action parameter to your request reflecting the function that you need to call in functions.php - let's call it create_user.

$.post(ajax_url, {action: 'create_user'} , function(data) {
  alert(data);
});

3. Create the function in functions.php

Inside functions.php, add the following:

function ajax_create_user() {
  $userid = new WP_User(wp_create_user( 'My_new_name' , '123458' , '[email protected]'));
  $userid->set_role('client');
  // echo whatever you need to return
}
add_action( 'wp_ajax_create_user', 'ajax_create_user' );
add_action( 'wp_ajax_nopriv_create_user', 'ajax_create_user' );

Read more about AJAX in Wordpress

Upvotes: 2

Related Questions