I am writing a WordPress theme that adds several custom fields to the user profile using the following function

function add_contact_methods( $profile_fields ) {
// Add Social Media Fields
$profile_fields['facebook']  = esc_html_e( 'Facebook URL', 'jldc' );
);

return $profile_fields;
}
add_filter( 'user_contactmethods', 'add_contact_methods' );

How do I hook this into the REST API (using v2-ßeta13 of the plug-in) so that the value of this field will be returned in the JSON response from the server?

I found one tutorial on it and I ended up with the resulting code:

function facebook_add_user_data() {
register_api_field( 'user',
    'facebook',
    array(
        'get_callback'  => 'facebook_get_user_field',
        'update_callback'   => null,
        'schema'            => array(
                                        'description'   => 'User Facebook URL',
                                        'type'          => 'string',
                                        'context'       => array( 'view' ),
                                ),
     )
);
}

add_action( 'rest_api_init', 'facebook_add_user_data' );

function facebook_get_user_field( $user, $field_name, $request ) {
    return get_user_meta( $user->id, $field_name);
}

When I run the request (../wp-json/wp/v2/users/2) the fields are not appearing.

How do you hook these fields in?

1 Answer
1

I got it. Turns out the tutorial I was looking at was old and I was using the wrong WP function. I was using register_api_field but the correct one to use is register_rest_field.

It goes like this…

function facebook_add_user_data() {
register_rest_field( 'user',
    'facebook',
    array(
        'get_callback'  => 'rest_get_user_field',
        'update_callback'   => null,
        'schema'            => null,
     )
);
}
add_action( 'rest_api_init', 'facebook_add_user_data' );

function rest_get_user_field( $user, $field_name, $request ) {
    return get_user_meta( $user[ 'id' ], $field_name, true );
}

I tried it out and the response from the server included the “facebook” field and the URL from the user’s profile.

Also, the facebook_get_user_field function can actually be reused so I renamed it rest_get_user_field and tested it with another field name nad it produced that data in the response too.

Leave a Reply

Your email address will not be published. Required fields are marked *