// _ _ ___ _____ _ _ _ _
// | | | | ___ ___ _ __ |_ _| _ __ | ___| ___ | | | | _ __ __| | __ _ | |_ ___
// | | | | / __| / _ \ | '__| | | | '_ \ | |_ / _ \ | | | | | '_ \ / _` | / _` | | __| / _ \
// | |_| | \__ \ | __/ | | | | | | | | | _| | (_) | | |_| | | |_) | | (_| | | (_| | | |_ | __/
// \___/ |___/ \___| |_| |___| |_| |_| |_| \___/ \___/ | .__/ \__,_| \__,_| \__| \___|
// |_|
// https://pahona.org/api/wp-json/custom/v1/update-user-info
function custom_user_update_endpoint() {
register_rest_route('custom/v1', '/update-user-info', array(
'methods' => 'POST',
'callback' => 'handle_user_update',
'permission_callback' => '__return_true',
'args' => array(
'first_name' => array(
'required' => false,
'type' => 'string',
'description' => 'The first name of the user',
),
'last_name' => array(
'required' => false,
'type' => 'string',
'description' => 'The last name of the user',
),
'marital_status' => array(
'required' => false,
'type' => 'string',
'description' => 'The marital status of the user',
),
'nid' => array(
'required' => false,
'type' => 'string',
'description' => 'The National ID of the user',
),
'contact_number' => array(
'required' => true,
'type' => 'string',
'description' => 'The contact number for the user',
),
),
));
}
add_action('rest_api_init', 'custom_user_update_endpoint');
function handle_user_update($request) {
$user = wp_get_current_user();
// Update user meta fields
if ($request->get_param('first_name')) {
update_user_meta($user->ID, 'first_name', sanitize_text_field($request->get_param('first_name')));
}
if ($request->get_param('last_name')) {
update_user_meta($user->ID, 'last_name', sanitize_text_field($request->get_param('last_name')));
}
if ($request->get_param('marital_status')) {
update_user_meta($user->ID, 'marital_status', sanitize_text_field($request->get_param('marital_status')));
}
if ($request->get_param('nid')) {
update_user_meta($user->ID, 'nid', sanitize_text_field($request->get_param('nid')));
}
// Always update contact number
$contact_number = sanitize_text_field($request->get_param('contact_number'));
if (!preg_match('/^[0-9]{11}$/', $contact_number)) {
return new WP_Error('invalid_contact_number', 'Invalid contact number format (should be 11 digits)', array('status' => 400));
}
update_user_meta($user->ID, 'contact_number', $contact_number);
return new WP_REST_Response(array('message' => 'User information updated successfully.'), 200);
}