Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Add user meta to the WP-API
<?php
/* Adds all user meta to the /wp-json/wp/v2/user/[id] endpoint */
function sb_user_meta( $data, $field_name, $request ) {
if( $data['id'] ){
$user_meta = get_user_meta( $data['id'] );
}
if ( !$user_meta ) {
return new WP_Error( 'No user meta found', 'No user meta found', array( 'status' => 404 ) );
}
foreach ($user_meta as $key => $value) {
$data[$key] = $value;
}
return $data;
}
add_action( 'rest_api_init', function () {
register_api_field( 'user',
'meta',
array(
'get_callback' => 'sb_user_meta',
'update_callback' => null, // add callback here for POST/PUT requests to update user meta
'schema' => null,
)
);
} );
@Yaffar

This comment has been minimized.

Copy link

@Yaffar Yaffar commented Sep 7, 2016

I used this code on my project and it works great, but I was wondering how can I update some of the meta through a POST method?

@radhitee

This comment has been minimized.

Copy link

@radhitee radhitee commented Feb 16, 2017

how to i put this code in my project?

@Wohlfarth

This comment has been minimized.

Copy link

@Wohlfarth Wohlfarth commented Nov 13, 2018

Works great thanks @scottopolis . I added it in the functions.php file as is and testing GET /wp-json/wp/v2/users/2 in Postman returns all the meta fields.

@patriciadenise99

This comment has been minimized.

Copy link

@patriciadenise99 patriciadenise99 commented Aug 18, 2019

How will I update the user meta?

@davykiala

This comment has been minimized.

Copy link

@davykiala davykiala commented Apr 18, 2020

@Wohlfath great ! Could you provide your functions.php please ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.