1. Home
  2. WordPress
  3. APi Development
  4. Get User Info Custom Format

Get User Info Custom Format

//   _   _                         ___           _____         
//  | | | |  ___    ___   _ __    |_ _|  _ __   |  ___|   ___  
//  | | | | / __|  / _ \ | '__|    | |  | '_ \  | |_     / _ \ 
//  | |_| | \__ \ |  __/ | |       | |  | | | | |  _|   | (_) |
//   \___/  |___/  \___| |_|      |___| |_| |_| |_|      \___/ 
//     
//                                                                                                                   

// https://pahona.org/api/wp-json/custom/v1/user-info/{id}
function custom_user_info_endpoint() {
    register_rest_route('custom/v1', '/user-info/(?P<id>\d+)', array(
        'methods' => 'GET',
        'callback' => 'get_user_info',
        'permission_callback' => '__return_true',
        'args' => array(
            'id' => array(
                'validate_callback' => function($param, $request, $key) {
                    return is_numeric($param);
                },
                'required' => true,
                'type' => 'integer',
                'description' => 'User ID',
            ),
        ),
    ));
}
add_action('rest_api_init', 'custom_user_info_endpoint');

function get_user_info($request) {
    $user_id = $request->get_param('id');
    $user = get_userdata($user_id);

    if (!$user) {
        return new WP_Error('user_not_found', 'User not found', array('status' => 404));
    }

    $response = array(
        'ID' => $user->ID,
        'username' => $user->user_login,
        'email' => $user->user_email,
        'first_name' => $user->first_name,
        'last_name' => $user->last_name,
        'contact_number' => get_user_meta($user->ID, 'contact_number', true),
        'nid' => get_user_meta($user->ID, 'nid', true),
        'marital_status' => get_user_meta($user->ID, 'marital_status', true),
        'roles' => $user->roles, // Adding user roles to the response
    );

    return new WP_REST_Response($response, 200);
}

How can we help?