wp_logout()
云策文档标注
概述
wp_logout() 函数用于注销当前登录用户,通过清除会话、Cookie 和重置用户状态来实现。开发者需注意其直接调用会导致立即注销,应谨慎使用以避免意外退出。
关键要点
- wp_logout() 注销当前用户,执行 wp_destroy_current_session()、wp_clear_auth_cookie() 和 wp_set_current_user(0) 操作
- 触发 'wp_logout' action hook,传递用户 ID 参数,允许开发者添加自定义注销逻辑
- 函数直接调用会立即生效,不适合用于按钮或小工具中,推荐使用 wp_logout_url() 创建安全注销链接
- 在 'wp_logout' hook 中,WP_User 对象可能已销毁,避免依赖用户角色等属性进行重定向
代码示例
// 示例:基于用户角色的注销后重定向(注意潜在问题)
function wpdocs_redirect_after_logout() {
$current_user = wp_get_current_user();
$role_name = $current_user->roles[0];
if ( 'subscriber' === $role_name ) {
$redirect_url = site_url();
wp_safe_redirect( $redirect_url );
exit;
}
}
add_action( 'wp_logout', 'wpdocs_redirect_after_logout' );注意事项
- 不要将 wp_logout() 直接嵌入按钮或小工具代码中,否则可能导致每次访问页面时自动注销,失去管理员访问权限
- 在 'wp_logout' hook 中,wp_get_current_user() 可能无法返回已注销用户信息,需谨慎处理用户数据
- 建议将 wp_logout() 包装在条件语句中,或使用 wp_logout_url() 生成安全的注销链接
原文内容
Logs the current user out.
Source
function wp_logout() {
$user_id = get_current_user_id();
wp_destroy_current_session();
wp_clear_auth_cookie();
wp_set_current_user( 0 );
/**
* Fires after a user is logged out.
*
* @since 1.5.0
* @since 5.5.0 Added the `$user_id` parameter.
*
* @param int $user_id ID of the user that was logged out.
*/
do_action( 'wp_logout', $user_id );
}
Hooks
- do_action( ‘wp_logout’, int $user_id )
-
Fires after a user is logged out.
Changelog
| Version | Description |
|---|---|
| 2.5.0 | Introduced. |
Skip to note 3 content
Ahir Hemant
Logout function according user role.
function wpdocs_redirect_after_logout() { $current_user = wp_get_current_user(); $role_name = $current_user->roles[0]; if ( 'subscriber' === $role_name ) { $redirect_url = site_url(); wp_safe_redirect( $redirect_url ); exit; } } add_action( 'wp_logout', 'wpdocs_redirect_after_logout' );object(WP_User)[947] public 'data' => object(stdClass)[948] public 'ID' => int 0 public 'caps' => array (size=0) empty public 'cap_key' => null public 'roles' => array (size=0) empty public 'allcaps' => array (size=0) empty public 'filter' => null private 'site_id' => int 0Skip to note 4 content
Codex
Example
wp_logout();should always be wrapped in an if statement.