Wordpress - How do I create a user using the new JSON api in 4.7?
The REST API included in WordPress doesn't actually have authentication built into it.
If you do normal authentication in WordPress by logging in, then your browser will receive a set of cookies. If you send those cookies along with your request, then that will authenticate you to perform the actions in question.
If you need to add authentication for an external service, then you need to install a plugin to handle it. A few are available:
- https://wordpress.org/plugins/rest-api-oauth1/
- https://wordpress.org/plugins/application-passwords/
- https://wordpress.org/plugins/jwt-authentication-for-wp-rest-api/
If you're just testing locally, there is also a Basic Authentication plugin which allows you to simply send your username and password with every request in an Authorization header:
- https://github.com/WP-API/Basic-Auth
In any case, once you've either gotten the proper cookie or enabled the authentication method, then creating a new user is simple. Send a POST request to /wp-json/wp/v2/users with the username, email, and password as the payload.
You can find this documented here:
https://developer.wordpress.org/rest-api/using-the-rest-api/
https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/
In order to ‘Register User’ or ‘Retrieve Password’, the authentication for a user with ‘Administrator’ role is required. While this is a delibrately done for security reasons, such implementation makes it very hard for Front End applications to implement a simple ‘Register’ or ‘Sign Up’ function.
The simple solution is use this wp-rest-user plugin. This plugin full fill such requirement by extending the existing WordPress REST API endpoints.
USAGE
Send a POST request to /wp-json/wp/v2/users/register
, including a JSON body with three keys: username, email and password.
Send a POST request to /wp-json/wp/v2/users/lostpassword
, including a JSON body with three keys: user_login.
You can use postman to as bellow picture
Or even ajax request, please see the code bellow
<script>
function addUserData(){
$.ajax( {
url: 'http://localhost/lapaktrip/wp-json/wp/v2/users/register',
method: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
data:JSON.stringify({
'username' : 'testmember',
'email' : '[email protected]',
'password' : '123456'
})
} ).done( function ( response ) {
console.log( response );
} )
}
</script>
<button onclick="addUserData()">Start Sending</button>
Hope this answer can help many people out there. Happy Codding.