WordPress’s robust user management system is an attributing factor to its overall success as a content management system. The WordPress REST API opens up a realm of new possibilities for this system, which makes WordPress a better, more powerful CMS.
With the capabilities of the REST API, WordPress’s user management can be leveraged in web applications. It also allows theme developers to create more dynamic links between content that will highlight the author and their posts. This article provides an introduction to working with user data via the WordPress REST API. You’ll also learn how to create a profile editor and viewer; which is fairly straightforward since the REST API does so much of the heavy lifting for us.
If you’ve worked with any of the other object types such as posts, terms, or comments, then working with user data should be familiar. If you haven’t, don’t worry, one of the many impressive features about version two of the REST API is that it’s very consistent in how each object is treated. This means that once you learn the pattern for one of the objects, you should easily be able to apply it to all of the objects.
Note: This article assumes that you’ve downloaded version two of the WordPress REST API plugin. You can install it via WordPress.org or clone the “develop” branch of the official GitHub repository for the project.
Retrieving User Data Via The API
Viewing Public User Data
In published posts, you can find a limited set of data for all users when making non-authenticated requests. This includes the user’s avatar in a variety of sizes, their username, ID and description, and the url for their author archive and website.
This data can be found for all users by making a GET request to “wp-json/wp/v2/users” or for a specific user by adding the user’s ID to the end of the url.
Keep in mind that when requesting all users, the results will be paged. You can control which pages of results will show up by using per_page and page arguments. For example, you can use “wp-json/wp/v2/users?page=2&per_page=10” to get the results for pages 11 through 20.
This code is a basic example that uses jQuery AJAX to list all users with published posts. The second step uses the posts endpoint to query by the author.
Although, tt’s a very basic example, when combined with some styling and a templating system, you could use it to build a directory system or a highly-dynamic author preview system. Be sure to explore the data available in the responses for users and posts, and try adding it to your markup.
If data you need is not available, keep in mind that adding fields to responses, using register_api_fields applies to user endpoints as well.
You can also use this code to create a modal with an author’s recent post that was populated asynchronously when you clicked on what is normally a link to the author’s post archive.
Viewing Privileged Data
So far we have only worked with publically available data. When you authenticate your request, you can add a query parameter “context” set to view more information about the user. This includes their capabilities and email address.
You can see the difference when authenticated as an admin by comparing the response of a GET request to “wp-json/wp/v2/user/1” to a request to “wp-json/wp/v2/users/1?context=view.” The former looks exactly like a non-authenticated request while the latter shows a lot more information.
As an admin, all users are available once you’re authenticated—not just those with public posts.
Editing Users Via The REST API
The REST API can also be used to update users. The same endpoints I showed earlier for viewing user data, can also be used to create and edit users.
For example, a POST request to “wp/v2/users” can be used to create a new user. When doing so, you must send at least a username, password, and email address. Here’s an example, using jQuery AJAX to create a user:
[js]
$.ajax( {
url: Slug_API_Settings.root + ‘wp/v2/users/’,
method: ‘POST’,
beforeSend: function ( xhr ) {
xhr.setRequestHeader( ‘X-WP-Nonce’, Slug_API_Settings.nonce );
},
data:{
email: ‘[email protected]’,
username: ‘someone’,
password: Math.random().toString(36).substring(7)
}
} ).done( function ( response ) {
console.log( response );
} )
[/js]
Keep in mind that this example and the next one, use cookie-based authentication with a nonce check, as documented here. This means it will only work when the current user is logged in and has the right capabilities to allow them to create users. If you are using a front-end decoupled from WordPress, you will need to use an alternative solution of for authentication. It also requires that you localize data for the nonce, root API url, and current user ID. Here’s my example:
[php]
add_action( ‘wp_enqueue_scripts’, function() {
wp_enqueue_script( ‘user-editor’, plugin_dir_url( __FILE__ ) .’user-editor.js’, array(‘jquery’) );
wp_localize_script( ‘user-editor’, ‘Slug_API_Settings’, array(
‘root’ => esc_url_raw( rest_url() ),
‘nonce’ => wp_create_nonce( ‘wp_rest’ ),
‘current_user_id’ => (int) get_current_user_id()
) );
});
[/php]
For a more complex example, create a form to update the current user’s email address. It will use the most basic HTML markup:
[html]
<form id="profile-form">
<div id="username"></div>
<input type="text" name="email" id="email">
<input type="submit">
</form>
[/html]
Assuming you have the same setup for your JavaScript as in the last example, here’s how to get the current user via the REST API and put that information into the form:
[js]
jQuery( document ).ready(function( $ ) {
$.ajax( {
url: Slug_API_Settings.root + ‘wp/v2/users/’ + Slug_API_Settings.current_user_id + ‘?context=edit’,
method: ‘GET’,
beforeSend: function ( xhr ) {
xhr.setRequestHeader( ‘X-WP-Nonce’, Slug_API_Settings.nonce );
}
} ).done( function ( user ) {
$( ‘#username’ ).html( ‘<p>’ + user.name + ‘</p>’ );
$( ‘#email’ ).val( user.email );
} );
});
[/js]
Upon page load, this makes a GET request for the current user and then adds their username and email to the form. Notice that I used ?conext=edit in the request. As I explained above, without it, only a limited response would be shown, which would not include the user’s email address.
To make this form work for updating a current user, a similar request can be made when the form is submitted, except it will be a POST request. Here is the JavaScript updated to do so:
[js]
jQuery( document ).ready(function( $ ) {
var get_user_data;
(get_user_data = function () {
$.ajax( {
url: Slug_API_Settings.root + ‘wp/v2/users/’ + Slug_API_Settings.current_user_id + ‘?context=edit’,
method: ‘GET’,
beforeSend: function ( xhr ) {
xhr.setRequestHeader( ‘X-WP-Nonce’, Slug_API_Settings.nonce );
}
} ).done( function ( user ) {
$( ‘#username’ ).html( ‘<p>’ + user.name + ‘</p>’ );
$( ‘#email’ ).val( user.email );
} );
})();
$( ‘#profile-form’ ).on( ‘submit’, function(e) {
e.preventDefault();
$.ajax( {
url: Slug_API_Settings.root + ‘wp/v2/users/’ + Slug_API_Settings.current_user_id,
method: ‘POST’,
beforeSend: function ( xhr ) {
xhr.setRequestHeader( ‘X-WP-Nonce’, Slug_API_Settings.nonce );
},
data:{
email: $( ‘#email’ ).val()
}
} ).done( function ( response ) {
console.log( response )
} )
});
});
[/js]
I encourage you to use what you’ve learned here to explore the available fields and add more capabilities to this simple setup.
Now Go Make Something Awesome!
In this article, you’ve learned the basics of viewing, updating and creating users via the WordPress REST API. I’ve shown all of my examples in jQuery to encourage you to use this to make your themes, apps, and plugins more dynamic.
Now it’s time for you to take what you’ve learned and apply it to what you’re working on and create exciting new interfaces for user management.
4 Comments