2

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?

  • then under $profile_fields['facebook'] = esc_html_e( 'Facebook URL', 'jldc' ); ); <-- is it typo too? – Jevuska Apr 10 '16 at 1:42
  • Last.. since you use get_user_meta, make sure to check key and value, is it exists in your database? – Jevuska Apr 10 '16 at 1:56
  • No, that's not a typo. That's how I had it in the original function. I'm using that function so it can be translated if needed. – Cedon Apr 10 '16 at 12:31
8

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.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.