Support » Plugin: WP REST API (WP API) » Registration and Examples

  • Resolved aryanduntley


    Does the plugin currently support user registration? Also, it would be nice to have a handful of examples for:
    1) Loging in/Authentication using php curl and/or other methods
    2) Registering new users using php curl and/or other methods
    3) Retrieving customized data with filters using php curl and/or other methods
    2)Posting a new post/custom post type with meta using php curl and/or other methods
    4)Editing a new post/custom post type with meta using php curl and/or other methods
    5)Deleting a new post/custom post type with meta using php curl and/or other methods
    6)Full CPT extension example.

    The documentation is seriously lacking, although I am aware that you guys are still building this thing out and are not at 1.0 yet.

Viewing 10 replies - 1 through 10 (of 10 total)
  • Ok, just went through the code. Post Meta is not yet available. Neither is registration. I’ll extend the api so I can use this now and make a new insert_post method that incorporates meta. It will just be an additional post parameter ‘post_meta” that accepts an array of key/value pairs. I may check to see if the keys exist already, but all of that will be accessible through a filter that passes the post ID after creation/editing of the post (I’m surprised you don’t already have that filter). I am also having to register a new endpoint for registration. Still need to work out how best to authorize. I’ll post code here as I build these things out for others to use if they are having similar needs.

    Ok, for those of you who need registration, here is what I have come up with. Please note that the methods below that are empty and do nothing have arguments passed that may not work. The api only sends certain data to certain functions (and “_” data to all), so the $data param will only be available to some of the methods (the ones responsible for creation/editing). This extension creates a new user with the data passed to it (ext_pass, ext_login, ext_nicename, ext_email, ext_display_name, ext_nickname, ext_first_name, ext_last_name) and also will create additional user meta under the key (as an array) $data[‘ext_usermeta’].

    Place in your functions/plugin file

    function user_mbpregistration($server) {
    	global $registration_api;
    	$registration_api = new User_ExtendRegister($server);
    	add_filter( 'json_endpoints', array($registration_api, 'registerRoutes') );
    add_action( 'wp_json_server_before_serve', 'user_mbpregistration' );

    This class is in it’s own file. In this case ‘class-wp-json-registration.php as defined in the action above.

    class User_ExtendRegister{
    	protected $server;
    	public function __construct(WP_JSON_ResponseHandler $server) {
    		$this->server = $server;
    	public function registerRoutes( $routes ) {
            $routes['/mbpusers'] = array(
                array( array( $this, 'mbpAllUsers'), WP_JSON_Server::READABLE ),
                array( array( $this, 'newMBPUser'), WP_JSON_Server::CREATABLE | WP_JSON_Server::ACCEPT_JSON ),
            $routes['/mbpusers/user/(?P<user>\d+)'] = array(
                array( array( $this, 'getMBPUser'), WP_JSON_Server::READABLE ),
                array( array( $this, 'editMBPUser'), WP_JSON_Server::EDITABLE | WP_JSON_Server::ACCEPT_JSON ),
                array( array( $this, 'deleteMBPUser'), WP_JSON_Server::DELETABLE ),
            return $routes;
    	public function mbpAllUsers($_headers, $data = ''){
    		//array (for Collections) or an object (for Entities).
    			$rettr = "This will eventually display some useful information. Your credentials are USR: " . $_SERVER['PHP_AUTH_USER'] . " PASS: " . $_SERVER['PHP_AUTH_PW'];
    		}else{$rettr = "You are not logged in. When you are logged in successfully, your credentials will be displayed here.";}
    		return array('returnedData'=>$rettr);
    	public function newMBPUser($data, $_headers){
    		if(!current_user_can('create_users')){return new WP_Error( 'json_cannot_publish', __( 'Sorry, you are not allowed to create new users' ), array( 'status' => 403 ) );}
    		unset( $data['ID'] );
    		$upass = empty($data['ext_pass'])?'':$data['ext_pass'];
    		$ulogin = empty($data['ext_login'])?'':$data['ext_login'];
    		$unice = empty($data['ext_nicename'])?$ulogin:$data['ext_nicename'];
    		$ueml = empty($data['ext_email'])?'':$data['ext_email'];
    		$udisplay = empty($data['ext_display_name'])?$ulogin:$data['ext_display_name'];
    		$unick = empty($data['ext_nickname'])?$ulogin:$data['ext_nickname'];
    		$ufirst = empty($data['ext_first_name'])?'':$data['ext_first_name'];
    		$ulast = empty($data['ext_last_name'])?'':$data['ext_last_name'];
    		if(!$upass){return new WP_Error('json_insert_error',  __('Password not passed, required.'), array( 'status' => 500));}
    		if(!$ulogin){return new WP_Error('json_insert_error',  __('Username not passed, required.'), array( 'status' => 500));}
    		if(!$ueml){return new WP_Error('json_insert_error',  __('Email not passed, required.'), array( 'status' => 500));}
    			$userdata = array(
    				"user_pass" => $upass,
    				"user_login" => $ulogin,
    				"user_nicename" => $unice,
    				"user_email" => $ueml,
    				"display_name" => $udisplay,
    				"nickname" => $unick,
    				"first_name" => $ufirst,
    				"last_name" => $ulast,
    				"description" => '',
    				"user_registered" => current_time('mysql', 1),
    				"role" => 'subscriber'
    			$newuID = wp_insert_user( $userdata );
    			if(is_wp_error( $newuID)){
    				return new WP_Error('json_insert_error',  $newuID->get_error_message(), array( 'status' => 500));
    			$umarray = $data['ext_usermeta'];
    			foreach($umarray as $k => $v){
    				$td = empty($v)?'':$v;
    				update_user_meta($newuID, $k, $td);
    		return apply_filters( 'json_register_newuser', array('userID'=> $newuID), $data);
    	public function getMBPUser($data, $_headers, $user){
    		//array (for Collections) or an object (for Entities).
    	public function editMBPUser($data, $_headers, $user){}
    	public function deleteMBPUser($data, $_headers, $user){}


    The array to be passed will look something like this before being serialized:

    $userparams = array(
    	'ext_pass' => 'fakerpasw',
    	'ext_login' => 'FAKERUNAME',
    	//'ext_nicename' => '',
    	'ext_email' => 'fake@faker.fake',
    	//'ext_display_name' => ,
    	//'ext_nickname' => ,
    	'ext_first_name' => 'FAKEGUEY',
    	'ext_last_name' => 'FAKINGNAME',
    	'ext_usermeta' => array(
    		'address' => '123 fake st.',
    		'city' => 'KA',
    		'state' => 'US',
    		'postalcode' => '92109',
    		'mobilenum' => '123-456-7890',
    		'carrier' => 'npt',
    		'dob' => '1/2/13',
    		'sex' => 'male',
    		'wanttext' => 'no',
    		'colorwant' => 'pink'

    For those of you having some trouble with the metadata and such for posts and types, until the final release is ready and so you don’t have to edit source files, create a duplicate of the class-wp-json-posts.php file and call it something else. Change the class name, then include it in your extensions function like listed below. Then you have to unhook the posts class call and rehook it to your new class. Now you can edit that file and not worry about updates interfering. You can now add meta data, allow for featured image uploads with posts (looking now, but don’t think it’s there yet), etc…

    function custom_class_api($server) {
    	global $userreg_api, $wp_json_posts;
    	remove_filter( 'json_endpoints', array( $wp_json_posts, 'registerRoutes' ), 0 );
    	$userreg_api = new User_NRegist($server);
    	$wp_json_posts = new MyCustom_Posts($server);
    	add_filter( 'json_endpoints', array($uderreg_api, 'registerRoutes') );
    	add_filter( 'json_endpoints', array($wp_json_posts, 'registerRoutes'), 0 );
    add_action( 'wp_json_server_before_serve', 'custom_class_api' );

    FYI, the media is uploaded during a new post entry. It’s done at the bottom of insert_post in the ‘json_insert_post’ hook. That hook is declared in plugin.php and calls ‘attachThumbnail’ in the wp-json-media class. Looking at that class, it seems as though there is an expected media id as a parameter in the data object[‘featured_image’]. This doesn’t seem to make a whole lot of sense unless it is expected that media must first be uploaded via the /media endpoint, the media id retrieved, then the media id provided as a data parameter in the new or updated post. Seems kind of round-about, but I’m not sure whether they can both be done at the same time. I will investigate and post here with finding for anyone interested.

    insert_post does not have new metadata insert with either new or updated posts. I created the class in the previous post and added: apply_filters(‘json_insertadd_postmeta’, $post_ID, $data, $update); after if ( is_wp_error( $post_ID ) ). It needs to be added here because you don’t need to add meta to a post id that doesn’t exits. So, if there is no error and you have a valid post id, you can add the filter for json_insertadd_postmeta. I am only passing $data and not $post because the $data variable will contain the meta by whatever method you choose to have it sent. In your hook, you will be able access that data and the post id and with those variables, update whatever post meta is passed in whatever way you feel is necessary.

    Hi dunar21,

    I totally agree in the API lacking documentation! I am totally stuck at the following, maybe you could help?

    How can I translate this curl command which works fine into an ajax call?

    curl --data '{"title": "Hello Updated new post with cats!"}'     -H "Content-Type: application/javascript"     --user username:password

    I tried unbelievably lot of different variations and just dispair now. See:


    Uhm, without going into the method of trying to send the same data via an ajax call, instead, all you have to do is put that into a php file, and use ajax to call that php file. So, you have ajax.js which calls middleman.php. middleman.php has the cul code you have listed, gets the data back into a variable and spits it out into the underverse where the ajax call can retrieve it and do with the returned data as you desire.

    Ok, that way I also do not have the password showing in the users browser!

    No idea how to put a curl command into php though. If you have an actual code example that would be great. Any example will do usually I can work it out from there.

    $ch = curl_init();
    // Disable SSL verification
    curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    // Will return the response, if false it print the response
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_VERBOSE, 1);
    // Set the url
    //curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    //curl_setopt($ch, CURLOPT_USERPWD, $creds);
    curl_setopt($ch, CURLOPT_URL,$url);
    //curl_setopt($ch, CURLOPT_COOKIEJAR, ‘/tmp/cookies.txt’);
    //curl_setopt($ch, CURLOPT_COOKIEFILE, ‘/tmp/cookies.txt’);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    //$fjj = base64_encode($username.”:”.$password);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(“Content-Type:application/json”, “Accept:application/json”, ‘Authorization:Basic ‘. base64_encode($username.”:”.$password)));
    //base64_decode base64_encode(
    //curl_setopt($ch, CURLOPT_HEADER, 1);
    //curl_setopt($ch, CURLOPT_POST, true);
    //curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
    curl_setopt($ch, CURLINFO_HEADER_OUT, true);
    /*$parameters = array(
    //’ID’ => [ <post id> ]
    ‘content_raw’ => ‘some stuff about the fake post’,
    //’post_name’ => slug,
    ‘title’ => ‘FAKER POST’,
    ‘status’ => ‘publish’,
    ‘type’ => ‘post’,//post_type
    ‘author’ => ‘6140’,
    //’ping_status’ => ,
    //’post_parent’ => ,
    //’menu_order’ => ,
    //’to_ping’ => ,
    //’pinged’ => ,
    //’post_password’ => ,
    //’guid’ => ,
    //’post_content_filtered’ => ,
    //’post_excerpt’ => ,
    //’post_date’ => ,
    //’post_date_gmt’ => ,
    //’comment_status’ => ‘open’,
    //’post_category’ => array(),
    //’tags_input’ => ‘tag,tag,tag’,
    //’tax_input’ => array(‘{taxonomy}’ => ” or array()),
    //’page_template’ => ,

    ); */
    /*$userparams = array(
    ‘test_pass’ => ‘fakerpasw’,
    ‘test_login’ => ‘FAKERUNAME’,
    //’test_nicename’ => ”,
    ‘test_email’ => ‘fake@faker.fake’,
    //’test_display_name’ => ,
    //’test_nickname’ => ,
    ‘test_first_name’ => ‘FAKEGUEY’,
    ‘test_last_name’ => ‘FAKINGNAME’,
    ‘test_usermeta’ => array(
    ‘address’ => ‘123 fake st.’,
    ‘city’ => ‘KA’,
    ‘state’ => ‘US’,
    ‘postalcode’ => ‘92109’,
    ‘mobilenum’ => ‘123-456-7890’,
    ‘carrier’ => ‘npt’,
    ‘dob’ => ‘1/2/13’,
    ‘sex’ => ‘male’,
    ‘wanttext’ => ‘no’,
    ‘colorwant’ => ‘pink’
    //$parameters = $userparams;
    //$json = json_encode($parameters);

    //$postArgs = ‘data=’ . $json;
    //curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
    // Execute
    $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $allinf = curl_getinfo($ch);
    var_dump(json_decode($result, true));//print_r($result);
    echo “some br tags”;
    echo $http_status . “some br tags”;

    Cool! Many thanks. I will give this a shot once I am back on that issue.


Viewing 10 replies - 1 through 10 (of 10 total)
  • The topic ‘Registration and Examples’ is closed to new replies.