$conf, $runtime; function_exists('chdir') AND chdir(APP_PATH); $r = 'mysql' == $conf['cache']['type'] ? website_set('runtime', $runtime) : cache_set('runtime', $runtime); } function runtime_truncate() { global $conf; 'mysql' == $conf['cache']['type'] ? website_set('runtime', '') : cache_delete('runtime'); } register_shutdown_function('runtime_save'); ?>rest api - How add meta fields to a user with the wp-api?|Programmer puzzle solving
最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

rest api - How add meta fields to a user with the wp-api?

matteradmin9PV0评论

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

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 ));
Share Improve this question edited Jul 18, 2017 at 20:42 Maarten Heideman asked Jul 18, 2017 at 15:37 Maarten HeidemanMaarten Heideman 3594 silver badges16 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 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.

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 ));
                }
Post a comment

comment list (0)

  1. No comments so far