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


About The Author
Cabe Nolan is the founder of WP Cover where he shares his insight into WordPress, development, & entrepreneurship. Outside of WPCover, Cabe continues to run a successful WordPress development firm, Bold City Design as well as a few high profile websites, Arrivala, Two Way Resume, Dock Skipper, and a successful outdoors brand, DolfinPack.







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

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:


<?php
/**
* Plugin Name: Create API Call - WP Cover
* Plugin URI: https://www.wpcover.com
* Description: Custom plugin by Cabe to do random repetitive tasks when and where I need it to be done. The "Heavy Lifter"
* Version: 1.0
* Author: Cabe Nolan
* Author URI: https://www.boldcitydesign.com
* License: GPL12
*/
 
/*---------------------------------------------------
add settings page to menu
----------------------------------------------------*/
function add_rstuff_import_page() {
add_submenu_page( 'tools.php', 'Do Random Stuff', 'Do Random Stuff', 'manage_options', 'import-rstuff', 'import_rstuff' );
}
add_action( 'admin_menu', 'add_rstuff_import_page' );
 
function import_rstuff() {
?>
 
<div class="wrap import-csv">
    <h2>Do Stuff</h2>
    <p>Click Process button to do whatever is below in your run process.</p>
<?php
    if ( isset( $_POST['_wpnonce-is-iu-import-users-users-page_import_cn'] ) ) {
    check_admin_referer( 'is-iu-import-users-users-page_import_cn', '_wpnonce-is-iu-import-users-users-page_import_cn' );
    
    //create user
    $api_response = wp_remote_post( 'https://www.YOURWEBSITE.com/wp-json/wp/v2/users', array(
		 	'headers' => 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;
	    
		}
    }
    ?>
 
    <form method="post" action="">
        <?php wp_nonce_field( 'is-iu-import-users-users-page_import_cn', '_wpnonce-is-iu-import-users-users-page_import_cn' ); ?>
        <p class="submit">
            <input type="submit" class="button-primary" value="Process Posts" />
        </p>
    </form>
<?php } ?>

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.


Share Your Thoughts

Leave a Reply

Your email address will not be published.


Related Stuff You Might Like







WordPress News, Tips, & Code Snippets

Join the WP Cover mailing list and get wordpress news, tips, code snippets, security warnings, and more delivered right to your inbox.  We won't flood your inbox, newsletters typically go out every 1-2 weeks unless it involves an important security release.

You have Successfully Subscribed!