WordPress REST API – Creating A User With Post Meta (Custom Fields)

Jun 06, 2018

WordPress REST API – Creating A User With Post Meta (Custom Fields)


This post was originally created on our sister site WP Cover.
View Original Article
June 6, 2018

This tutorial is Part 2 to my initial post published last week on creating a post using the WP REST API.  If you haven’t ready it first, I would highly suggest you do so or this post will not make sense.

This post will use basically the exact same call as creating a post but with a different endpoint and our body paramters will be different.  Let’s jump in.

Here is how your ‘Do Random Stuff’ plugin code should look:



 

Do Stuff

Click Process button to do whatever is below in your run process.

array( 'Authorization' => 'Basic ' . base64_encode( 'USERNAME:APPLICATION_PASSWORD' ) ), 'body' => array( 'username' => 'testuser', 'first_name' => 'Jane', 'last_name' => 'Doe', 'email' => '[email protected]', 'password' => 'thebestpassword87&*&*^', 'roles' => array('subscriber'), 'meta' => array('user_associated' => 'CNENT') ) ) ); $body = json_decode( $api_response['body'] ); if($body->code == 'existing_user_login') { echo 'A user already exists with this login.'; } else { $userid = $body->id; echo 'The user ID is: ' . $userid; } } ?>

As with our previous tutorial, you’ll want to modify the wp_remote_post URL to match your WordPress Site A address. You’ll also want to swap out the username and application password you created in part one of this tutorial.

Feel free to change any of the user parameters listed in the body as well as add ‘meta’ values. As when we created a post in the first tutorial, these custom user fields should already be created either using a plugin such as Advanced Custom Fields or using native WordPress functions.

Before performing our test, we’ll need to add another function to Site A’s function.php file just as we did when creating a post. This will handle the user meta values that we’re passing. It is:

add_action("rest_insert_user", function (WP_User $user, $request, $creating) {
    $metas = $request->get_param("meta");
    if (is_array($metas)) {
        foreach ($metas as $name => $value) {
            update_user_meta($user->ID, $name, $value);
        }
    }
}, 10, 3);

All Set

Give that bad boy a test and see what happens. If all goes well, you should receive a response along the lines of, The user ID is: (user ID). If you instead receive a response that states, “A user already exists with this login”, it means exactly that. A user already exists on Site A with that login. You’ll need to decide yourself how you wish to handle.

The post WordPress REST API – Creating A User With Post Meta (Custom Fields) appeared first on WP Cover.

Additional News

Perfect!

Let's get started. Fill out the form below to email us or request a call back.