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;

wp_redirect(  wc_get_page_permalink( 'myaccount' ) );
add_action('wp_logout', 'do_anything');
  • Where are you using this code?
    – mikerojas
    Feb 23, 2021 at 14:44
  • in child theme in function.php Feb 23, 2021 at 14:46
  • Where though? In a function? The logged in user isn't set when functions.php so you can only use it in a hook that will run later. Feb 23, 2021 at 14:50
  • I created a function and I call it when the user logout. I added the full code in the question. Feb 23, 2021 at 15:01

1 Answer 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' );
  • Perfect solution!!! You converted my 15-20 line code to 1-line Thank you! Feb 23, 2021 at 15:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.