1

How add, update and retrieve user meta fields with the wp api? I added a function to add a meta field phonenumber to a user. Is a function like this necessary to add meta values to the meta object? The function doesn't add the field to the meta object in the API response but adds it as a new field.

The function i have right now:

<?php
function portal_add_user_field() {
    register_rest_field( 'user', 'phonenumber',
        array(
            'get_callback'      => function( $user, $field_name, $request ) {
                return get_user_meta( $user[ 'id' ], $field_name, true );
            },
            'update_callback'   => function( $user, $meta_key, $meta_value, $prev_value ) {
                $ret = update_user_meta( array( $user, $meta_key, $meta_value );
                return true;
            },
            'schema'            => array(
                'description'   => __( 'user phonenumber' ),
                'type'          => 'string'
            ),
         )
    );
}
add_action( 'rest_api_init', 'portal_add_user_field' );

I also tried to add the phone number field to the user meta with ajax without a extra function like this: (this doesn't save the phone number field)

updateUser: function () {
                   var data = {
                       username: this.username,
                       email: this.email,
                       first_name: this.firstname,
                       last_name: this.lastname,
                       meta: {
                        phonenumber: this.phonenumber
                      }
                   };
                   console.log(data);
                   $.ajax({
                       method: "POST",
                       url: wpApiSettings.current_domain + '/wp-json/wp/v2/users/' + wpApiSettings.current_user.ID,
                       data: data,
                       beforeSend: function ( xhr ) {
                           xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
                       }
                   })
                   .done( $.proxy( function() {
                       alert('Account saved');
                   }, this ))
                   .fail( $.proxy( function( response ) {
                       alert('something went wrong');
                   }, this ));

2 Answers 2

7

I have managed to do this with hooking into rest_insert_user. I send an array like this:

var data = {
       first_name: user.first_name,
       last_name: user.last_name,
       name: user.display_name,
       email: user.email,
       description: user.description,
       meta: {
        'wpcf-phone': user.phone,
        'wpcf-institution': user.institution,
        'wpcf-birthday': Math.round(new Date(user.birthday).getTime()/1000)
      }
   };

And treat only the meta data through the hook as this:

function aa_user_update($user, $request, $create)
{
    if ($request['meta']) {
        $user_id = $user->ID;
        foreach ($request['meta'] as $key => $value) {
            update_user_meta( $user_id, $key, $value );
        }
    }
}
add_action( 'rest_insert_user', 'aa_user_update', 12, 3 );

The ordinary fields of the user are updated normally by the API.

1
  • Worked like a charm. I have added the action and function in functions.php file of active theme. Commented Nov 18, 2022 at 10:03
1

found it, first yes for meta data on a user you'll need a custom function like this:

<?php
function portal_add_user_field() {
    register_rest_field( 'user', 'userfields',
        array(
            'get_callback'      => function( $user, $field_name, $request ) {
                return get_user_meta( $user[ 'id' ], $field_name, true );
            },
            'update_callback'   => function($meta_value ) {
                $havemetafield  = get_user_meta(1, 'userfields', false);
                if ($havemetafield) {
                    $ret = update_user_meta(1, 'userfields', $meta_value );
                    return true;
                } else {
                    $ret = add_user_meta( 1, 'userfields', $meta_value ,true );
                    return true;
                }
            },
            'schema'            => null
         )
    );
}
add_action( 'rest_api_init', 'portal_add_user_field', 10, 2 );

?>

after that with ajax send it like this:

updateUser: function () {
                   var data = {
                       userfields: {
                        somefield: this.somefield,
                        somefield2: this.somefield2
                      }
                   };
                   console.log(data);
                   $.ajax({
                       method: "POST",
                       url: wpApiSettings.current_domain + '/wp-json/wp/v2/users/' + wpApiSettings.current_user.ID,
                       data: data,
                       beforeSend: function ( xhr ) {
                           xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
                       }
                   })
                   .done( $.proxy( function() {
                       alert('Account saved');
                   }, this ))
                   .fail( $.proxy( function( response ) {
                       alert('something went wrong');
                   }, this ));
                }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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