我知道这个问题已经经常被问到了,但是is no exact answer for it.
我需要获取loggedin用户id来更改该用户在数据库中的值。
我试了两种方法都没用。
方式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\';";
方式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\';";
完整代码:
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\');
最合适的回答,由SO网友:Jacob Peattie 整理而成
您正在wp_loguout
钩子,这是在用户注销之后,所以当然没有当前用户ID。根本没有当前用户。
如果你看the documentation 对于wp_logout
钩子,您将看到注销用户的ID被传递给任何钩子函数。如果希望注销用户的ID:
function do_anything( $user_id ) {
// $user_id is now the logged out user\'s ID.
}
add_action( \'wp_logout\', \'do_anything\' );
此外,如果要更新用户meta,您确实不应该创建到数据库的新连接并使用SQL。你应该使用正确的功能,
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\' );