简体   繁体   中英

Can't update custom user meta through Wordpress REST API

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM