Sometimes we may need to add custom fields to existing core WordPress REST API, which we may also need in the wp.data
module for Custom Gutenberg Block development.
In this blog we will learn about how to do just that.
Add custom field to ‘user’ endpoint.
We will use register_rest_field
function and hook it to rest_api_init
hook. So add this to your functions.php
add_action( 'rest_api_init', 'adding_user_meta_rest' );
/**
* Adds user_meta to rest api 'user' endpoint.
*/
function adding_user_meta_rest() {
register_rest_field( 'user',
'user_meta',
array(
'get_callback' => 'user_meta_callback',
'update_callback' => null,
'schema' => null,
)
);
}
/**
* Return user meta object.
*
* @param array $user User.
* @param string $field_name Registered custom field name ( In this case 'user_meta' )
* @param object $request Request object.
*
* @return mixed
*/
function user_meta_callback( $user, $field_name, $request) {
return get_user_meta( $user['id'] );
}
Access registered field using REST API
Let’s hit the following endpoint in the browser /wp-json/wp/v2/users/
Access registered field using WordPress Data module.
You can now access the user field in WordPress data module for block development as well.
Let’s run this in console on the WordPress editor page.
wp.data.select('core').getCurrentUser();
That’s all folks