Reputation: 1272
I am working on a site that gets and updates content through the Wordpress REST API. I'm trying to update a user's bookmarks whenever the user clicks on a "Bookmark this" button, so I have created the following register_rest_field
function:
function handle_user_bookmarks() {
register_rest_field( 'user', 'bookmarks', array(
'get_callback' => array( $this, 'get_user_bookmarks' ),
'update_callback' => array( $this, 'add_user_bookmarks' ),
'schema' => null
));
}
function get_user_bookmarks( $user, $field_name, $request ) {
return get_user_meta( $user[ 'id' ], $field_name, true );
}
function add_user_bookmarks( $user, $meta_value ) {
$bookmarks = get_user_meta( $user[ 'id' ], 'bookmarks', false );
if( $bookmarks ) {
update_user_meta( $user[ 'id' ], 'bookmarks', $meta_value );
} else {
add_user_meta( $user[ 'id' ], 'bookmarks', $meta_value, true );
}
}
The get_user_bookmarks
callback works fine; instead, the add_user_bookmarks
callback only works if I replace $user[ 'id' ]
with a "static" ID in the get_user_meta
, update_user_meta
and add_user_meta
. In other words, it works if coded as follows:
function add_user_bookmarks( $user, $meta_value ) {
$bookmarks = get_user_meta( 1, 'bookmarks', false );
if( $bookmarks ) {
update_user_meta( 1, 'bookmarks', $meta_value );
} else {
add_user_meta( 1, 'bookmarks', $meta_value, true );
}
}
The problem is clearly with the user ID, so how can I retrieve it in the add_user_bookmarks
callback?
Here's the HTTP request made at the click of the button, if that should help:
http://example.com/wp-json/wp/v2/users/1 (1 is the queried user's ID)
Upvotes: 1
Views: 2813
Reputation: 1272
Found it. I replaced $user['id']
with $user->ID
(in the add_user_bookmarks
only) and boom, it worked. So the working code is:
function handle_user_bookmarks() {
register_rest_field( 'user', 'bookmarks', array(
'get_callback' => array( $this, 'get_user_bookmarks' ),
'update_callback' => array( $this, 'add_user_bookmarks' ),
'schema' => null
));
}
function get_user_bookmarks( $user, $field_name, $request ) {
return get_user_meta( $user[ 'id' ], $field_name, true );
}
function add_user_bookmarks( $user, $meta_value ) {
$bookmarks = get_user_meta( $user->ID, 'bookmarks', false );
if( $bookmarks ) {
update_user_meta( $user->ID, 'bookmarks', $meta_value );
} else {
add_user_meta( $user->ID, 'bookmarks', $meta_value, true );
}
}
Upvotes: 4