I know that this question is already often asked but there is no exact answer for it.
I need to get the loggedin user id to change a value in the database for this user.
I tried 2 ways it didn’t work.
Way 1:
$user = get_current_user_id(); $sql = "UPDATE table_usermeta SET meta_value = '0' WHERE user_id= $user AND meta_key = 'alg_wc_ev_is_activated';";
Way 2:
$user = wp_get_current_user();
$user_id = $user->ID;
$sql = "UPDATE table_usermeta SET meta_value = '0' WHERE user_id= $user_id AND meta_key = 'alg_wc_ev_is_activated';";
Full code:
function do_anything() {
$servername = "localhost";
$user = get_current_user_id();
echo $user;
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE table_usermeta SET meta_value = '0' WHERE user_id= $user->ID AND meta_key = 'alg_wc_ev_is_activated';";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
wp_redirect( wc_get_page_permalink( 'myaccount' ) );
exit();
}
add_action('wp_logout', 'do_anything');
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
You’re running your code on the wp_loguout hook, which is after the user has logged out, so of course there’s no current user ID. There’s no current user at all.
If you look at the documentation for the wp_logout hook, you will see that the ID of the user that was logged out is passed to any hooked functions. You need to use that if you want the logged out user’s ID:
function do_anything( $user_id ) {
// $user_id is now the logged out user's ID.
}
add_action( 'wp_logout', 'do_anything' );
Also, you really should not be creating a new connection to the database and using SQL if you want to update user meta. You should be using the proper function, update_user_meta():
function do_anything( $user_id ) {
update_user_meta( $user_id, 'alg_wc_ev_is_activated', '0' );
// etc.
}
add_action( 'wp_logout', 'do_anything' );
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