I like the idea, but allowing to set any valid meta could be dangerous (“Mass Assignment Vulnerability”). For example, an attacker could set its “capabilities” meta to “admin”.
Instead, you could use a whitelist of allowed extra fields. You could set them either on a settings page or through a filter. Just an idea though, actually I would be happy if this plugin could accept some simple basic extra fields, the ones from get_userdata()
.
For now, this is how I include “first_name” and “last_name”:
/** Custom extra fields on user registration. */
add_filter( 'rest_pre_dispatch', 'ru_rest_store_request', 10, 3 );
add_action( 'wp_rest_user_user_register', 'ru_api_custom_fields_users' );
/** Save $request in a property, so it can be used on later actions (<code>api_custom_fields_users</code>). */
function ru_rest_store_request( $result, $server, $request ) {
global $rest_request;
$rest_request = $request; /* save $request. */
return $result;
}
/** Called on register user - add extra custom fields. */
public function ru_api_custom_fields_users( $user ) {
global $rest_request;
$parameters = $rest_request->get_json_params();
$first_name = sanitize_text_field( $parameters['first_name'] );
$last_name = sanitize_text_field( $parameters['last_name'] );
/** Add it as meta records. */
add_user_meta( $user->ID, 'first_name', $first_name, true );
add_user_meta( $user->ID, 'last_name', $last_name, true );
/** Update user record. */
$user->first_name = $first_name;
$user->last_name = $last_name;
wp_update_user( $user );
}
This code saves “first_name” and “last_name” passed on the HTTP request.