Your cart is currently empty!
Article: Don’t use saveEntityRecord for saving user meta within WordPress Gutenberg
New Day: Sun Apr 02 2023 15:34:55 GMT-0500 (Central Daylight Time)
I am trying to get something like this working:
I tried to use saveEntityRecord for changing user meta and it didn’t work. In order to change user meta you have to register_meta in php with show in rest set to true. Then, use a POST request to post to the endpoint with the body of the message with the meta_key you would like to change.
The PHP:
/**
* Register user meta which will be changed via REST call.
*/
function my_register_user_meta() {
register_meta(
'user',
'my_meta_key',
array(
'type' => 'string',
'description' => 'My User Meta',
'single' => true,
'show_in_rest' => true,
'sanitize_callback' => 'sanitize_text_field',
)
);
}
add_action( 'init', __NAMESPACE__ . '\my_register_user_meta' );
The JavaScript:
userDataThree = {
meta: {
'my_meta_key': 'my_new_meta_value'
}
};
fetch('/wp-json/wp/v2/users/2', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-WP-Nonce': wpApiSettings.nonce // replace with your WordPress nonce
},
body: JSON.stringify(userDataThree)
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
Getting Ahead: Your first 2,000 dollars on Upwork
Are you a developer dreaming of location independence and a lucrative career? This ebook is your roadmap to success on Upwork, one of the world’s leading freelance platforms. Whether you’re a seasoned coder or just starting out, we’ll guide you through the most effective strategies to reach that crucial $2,000 milestone.