WordPress 禁止多个人同时登录一个账号

对于开放注册的 WordPress 站点来说,尤其是有会员购买服务的站点,可能需要禁止用户共享账号,也就是要禁止多个人同时登录一个账号。倡萌今天分享老外的一个方法,大家不妨试试。

将下面的代码到主题的 functions.php 中即可:

/**
 * Detect if the current user has concurrent sessions
 *
 * @return bool
 */
function pcl_user_has_concurrent_sessions() {
	return ( is_user_logged_in() && count( wp_get_all_sessions() ) > 1 );
}
 
/**
 * Get the user's current session array
 *
 * @return array
 */
function pcl_get_current_session() {
	$sessions = WP_Session_Tokens::get_instance( get_current_user_id() );
 
	return $sessions->get( wp_get_session_token() );
}
 
/**
 * Only allow one session per user
 *
 * If the current user's session has been taken over by a newer
 * session then we will destroy their session automattically and
 * they will have to login again to continue.
 *
 * @action init
 *
 * @return void
 */
function pcl_disallow_account_sharing() {
	if ( ! pcl_user_has_concurrent_sessions() ) {
		return;
	}
 
	$newest  = max( wp_list_pluck( wp_get_all_sessions(), 'login' ) );
	$session = pcl_get_current_session();
 
	if ( $session['login'] === $newest ) {
		wp_destroy_other_sessions();
	} else {
		wp_destroy_current_session();
	}
}
add_action( 'init', 'pcl_disallow_account_sharing' );

如果大家不想折腾代码,可以直接下载插件 Prevent Concurrent Logins 安装启用也是一样的。

本文转自:https://www.wpdaxue.com/prevent-concurrent-logins.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值