Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
WP - update user and keeps him login with ability to make more requests without page refresh.
<?php
function my_update_cookie( $logged_in_cookie ) {
$_COOKIE[ LOGGED_IN_COOKIE ] = $logged_in_cookie;
}
add_action( 'set_logged_in_cookie', 'my_update_cookie' );
wp_localize_script(
'theme_js',
'theme_data',
array(
'nonce' => wp_create_nonce( 'wp_rest' )
)
);
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
window.axios.defaults.headers.common['X-WP-Nonce'] = window.theme_data.nonce;
async updateProfile() {
try {
const res = await this.form.post(url);
//setting new nonce
window.axios.defaults.headers.common['X-WP-Nonce'] = res.data;
} catch (e) {
}
},
<?php
function api_update_profile( WP_REST_Request $request ) {
if( !is_user_logged_in() ) {
$error = 'Unauthorized';
return new WP_Error( 'update_profile_errors', $error, ['status' => 500] );
}
$user = wp_get_current_user();
$display_name = sanitize_text_field( trim( $request['display_name'] ) );
$email = sanitize_email( trim( $request['email'] ) );
$current_password = sanitize_text_field( trim( $request['current_password'] ) );
$new_password = sanitize_text_field( trim( $request['new_password'] ) );
$confirm_new_password = sanitize_text_field( trim( $request['confirm_new_password'] ) );
$errors = [];
$user_login = $user->user_login;
if( empty( $display_name ) ) {
$errors["display_name"] = "Display Name is required";
}
if( email_exists( $email ) && $email !== $user->user_email ) {
$errors["email"] = "Email exists already";
}
if( empty( $email ) || ! is_email( $email ) ) {
$errors["email"] = "Valid Email is required";
}
if($new_password || $confirm_new_password) {
if (! wp_check_password( $current_password, $user->user_pass, $user->ID ) ) {
$errors["current_password"] = "Invalid password";
}
if( $new_password !== $confirm_new_password ) {
$errors["confirm_new_password"] = "Password confirmation don't match";
}
if( strlen( $new_password ) < 6 ) {
$errors["new_password"] = "Password must be at least 6 characters";
}
if ( ! count( $errors ) ) {
wp_set_password( $new_password, $user->ID );
}
}
if( count( $errors ) > 0 ) {
return new WP_Error( 'update_profile_errors', $errors, ['status' => 422] );
}
$user_id = wp_update_user( [
'ID' => $user->ID,
'user_email' => $email,
'display_name' => $display_name,
] );
if ( is_wp_error( $user_id ) ) {
$error = "Something went wrong. Please try again, or contact us if it continues.";
return new WP_Error( 'update_profile_errors', $error, ['status' => 500] );
}
wp_cache_delete( $user->ID, 'users' );
wp_cache_delete( $user_login, 'userlogins' ); //original user_login
wp_set_auth_cookie( $user->ID, true );
return wp_create_nonce( 'wp_rest' );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment