如何使用wp-api向用户添加元字段?

时间:2017-07-18 作者:Maarten Heideman

如何使用wp api添加、更新和检索用户元字段?我添加了一个函数来向用户添加元字段phonenumber。这样的函数是否需要向元对象添加元值?该函数不会将字段添加到API响应中的元对象,而是将其作为新字段添加。

我现在拥有的功能:

<?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\' );
我还尝试使用ajax将电话号码字段添加到用户元中,但没有这样的额外功能:(这不会保存电话号码字段)

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 个回复
最合适的回答,由SO网友:Maarten Heideman 整理而成

找到它,首先是对于用户上的元数据,您需要这样一个自定义函数:

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

之后,使用ajax发送如下内容:

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

SO网友:Guilherme Sampaio

我成功地做到了这一点rest_insert_user.我发送如下数组:

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)
      }
   };
并仅通过钩子处理元数据,如下所示:

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 );
用户的普通字段通常由API更新。

结束

相关推荐

Php致命错误:无法将WP_REST_RESPONSE类型的对象用作wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php中

我向WordPress添加了一个自定义端点,如下所示: add_action( \'rest_api_init\', function () { register_rest_route( \'menc/v1\', \'/crosscat/(?P[\\w-]+)/(?P[\\w-]+)\', array( \'methods\' => \'GET\', \'callback\' => \'dept_cat_api\',&#x