Update user meta via REST API?

I had to do this yesterday, here’s how I did it.

Like you have already done register_meta to appear in the api.

register_meta('user', 'meta_key', array(
    "type" => "string",
    "show_in_rest" => true,
    "single" => true,
));

Then you will need to make a POST or PUT request to the users endpoint with the meta values in the body of the request.

I accomplished this using javascript’s fetch api but you could also do it with ajax or using WordPress’s wp_remote_request() function.

First I enqueued my javascript.

wp_register_script( 'theme-js', get_theme_file_uri( './dist/scripts/main.js' ), [ 'jquery' ], '', true );
wp_localize_script(
    'theme-js',
    'wpApiSettings',
    array(
        'root'        => esc_url_raw( rest_url() ), // Rest api root
        'nonce'       => wp_create_nonce( 'wp_rest' ), // For auth
        'currentUser' => get_current_user_id() ?: false,
    )
);
wp_enqueue_script( 'theme-js' );

Then I setup my fetch function.

const fetchApi = function(route, data, method) {
  if (!route) route="posts"
  if (!method) method = 'GET'

  return fetch(wpApiSettings.root + 'wp/v2/' + route, {
    method,
    credentials: 'same-origin',
    body: JSON.stringify(data),
    headers: {
      'X-WP-Nonce': wpApiSettings.nonce,
      'Content-Type': 'application/json'
    }
  })
}

Then call the function when you need.

fetchApi(
  `users/${wpApiSettings.currentUser}`,
  {
    meta: {
      meta_key: value
    }
  },
  'POST'
)
  .then(resp => {
    console.log(resp)
    if (resp.ok) {
      return resp.json()
    }
    return false
  })
  .then(json => console.log(json))

error code: 523