我正在尝试从我的 WordPress 网站前端禁用管理员登录,但我的后端登录也被禁用,两个登录都显示管理员无法在此处登录
<?php
add_filter( 'authenticate', 'wp_admin_prevent_authentication', 30, 3 );
function wp_admin_prevent_authentication( $user, $username, $password ) {
if ( $user instanceof WP_User && is_page( 'my-account' ) ) {
if ( array_intersect( (array) $user->roles, [ 'administrator' ] ) ) {
return new WP_Error( 'admin-error', 'Admins cannot login from here.' );
};
};
return $user;
};
不确定您可以在
is_page()
内使用authenticate
,但您可以使用$_SERVER['REQUEST_URI']
获取页面名称。检查下面的代码。
function wp_admin_prevent_authentication( $user, $username, $password ) {
$url = explode( '/', rtrim( $_SERVER['REQUEST_URI'], '/') );
// If in My account dashboard page
if( $user instanceof WP_User && end( $url ) == 'my-account' ){
if ( array_intersect( (array) $user->roles, [ 'administrator' ] ) ) {
return new WP_Error( 'admin-error', 'Admins cannot login from here.' );
}
}
return $user;
}
add_filter( 'authenticate', 'wp_admin_prevent_authentication', 30, 3 );
已测试且有效。
您可以尝试使用下面的代码,也许它对您有用。
function wpum_admin_prevent_authentication( $user, $username, $password ) {
if ( $user instanceof WP_User && is_page( wpum_get_core_page_id( 'login' ) ) ) {
if ( array_intersect( (array) $user->roles, [ 'administrator' ] ) ) {
return new WP_Error( 'admin-error', 'Admins cannot login from here.' );
}
}
return $user;
}
add_filter( 'authenticate', 'wpum_admin_prevent_authentication', 30, 3 );