0

I have a native app project that gets all data from /wp-json/wp/v2.

I've registered phone using this

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

to the functions.php and I can see the user metadata using this

http://example.com/wp-json/wp/v2/users/1

How can I create/update the usermeta using WP REST API outside WordPress?

any help will be great.

Thanks

0

I found these 2 post helpful

0

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))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.