Search code examples
angularjswordpresswp-api

wp-api : How can I update user meta?


Right now, I can retrieve users like this ( via Angularjs and angular-wp-api ): [everything is written in coffee here]

req=
  method: 'GET'
  url: wpAPIData.base + "/users/me"
  headers:
    'X-WP-Nonce': wpAPIData.nonce

$http(req).success($scope.getData)

I can also update simple attrs of any user with this :

req=
  method: 'POST'
  url: wpAPIData.base + "/users/1"
  headers:
    'X-WP-Nonce': wpAPIData.nonce
  data:
    lastname: 'new name'
$http(req).success($scope.checkData)

The problem is, I don't find any way to update user meta within the wp api docs: http://wp-api.org/


Solution

  • So, as far as I know, there is nothing implemented right now on wp-api about metadata, you cannot retrieve metadata nor change them with the base api. However, you can extend the api to implement such functions.

    I based my dirty extending of the api on this post :
    https://github.com/WP-API/WP-API/issues/331

    If you want to do a proper extending of the api, follow his steps. A simplified version, and NOT MAINTAINABLE is to add a few lines in the class-wp-json-users.php, located in "wp-content/plugins/json-rest-api/libs/". You have to edit two functions in this file:

    • First, add this to prepare_user() to retrieve the true user metadata:

      $user_fields['meta'] = array(
          'meta' => get_user_meta($user->ID), /* This is the added line */
          'links' => array(
              'self' => json_url( '/users/' . $user->ID ),
              'archives' => json_url( '/users/' . $user->ID . '/posts' ),
          ),
      );
      

      It's filled with a lot of unnecessary info for you, free to you to sort out useless infos.

    • Second, add this to edit_user() in the first part of the function( you can also add similar lines into create_user if you need initial metadata ) :

      if(isset($data['metaupdate'])){
          foreach($data['metaupdate']as $k => $v){
              update_user_meta($user->ID,$k,$v);
          }
      }
      

    Here 'metaupdate' is the key used in the data sent by your PUT requests that will identify as the metadata you want to update. You can use any name of your liking for this. this key is an object containing every pair of key and value metadata that will be passed to the user.

    This is really dirty, and I'd heavily recommend you to opt for the above link implementation, since you won't be able to update anymore wp-api after this.