首页 > 解决方案 > 如何从前端禁用管理员登录?

问题描述

我正在尝试从我的 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;
};

标签: wordpressauthenticationwoocommerce

解决方案


不确定您是否可以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 );

测试和工作。

在此处输入图像描述


推荐阅读