Get user first name from custom endpoint

I am trying to set up a custom endpoint which only returns some user data instead of the default data sent back by the users endpoint. But I don’t know how to get the first and last name of the user from WP_User_Query

add_action( 'rest_api_init', function () {
  register_rest_route( 'myplugin/v1', 'some-endpoint', array(
    'methods' => 'GET',
    'callback' => 'my_awesome_func',
  ) );
} );

function my_awesome_func( $request) {

            $user_fields = array( 'user_nicename', 'user_url', 'first_name' );
            $wp_user_query = new WP_User_Query( array( 'role' => 'subscriber', 'fields' => $user_fields ) );
            $members = $wp_user_query->get_results();

    return new WP_REST_Response(
        array(
            'status' => 200,
            'response' => $members
        )
    );
    
    return $response;
}

If I remove ‘first_name’ from my array then I get back user_nicename and user_url in the response for all users. But with first_name in there I just get an empty response. I also tried firstname instead of first_name but still no joy.

Also, this only returns a handful of users. How do I show them all or 10, 20, 30 etc.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

If you look at the documentation, first_name is not in the list of accepted values for the fields parameter, and if you enabled debugging, you’d see adding first_name to that parameter would actually cause a database error — Unknown column 'wp_users.first_name' in 'field list'. And the same goes to the “firstname” and any other non-standard values.

So as the documentation says, “You must create a second query to get the user meta fields by ID or use the __get PHP magic method to get the values of these fields.“, you would need to manually add the first_name item to your $members array like so:

// &$member means we're modifying the original $members array
foreach ( $members as &$member ) {
    $member->first_name = get_user_meta( $member->ID, 'first_name', true );
}

But make sure ID is in the field list, e.g. $user_fields = array( 'user_nicename', 'user_url', 'ID' );.

And as for controlling the number of results, check the pagination parameters like number:

// Get at most 10 users (per page).
$user_query = new WP_User_Query( array( 'number' => 10 ) );

And BTW, remember to set permission_callback for your custom REST API endpoint.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x