2

When an external user or non admin tries to access http://www.urlVisibleToUsers.com/wp-admin gets re-directed to an error page, but still the home_url (where the WP installation resides) is exposed and visible. I would like to be able to re-direct all the end users or any role that is not an admin to http://www.urlVisibleToUsers.com/ and preventing adjax calls from breaking. I have the below code in my functions.php, but still an external user will see the home_url address in the navigation bar (although an error page is displayed):

add_action( 'admin_init', 'admin_area_for_manage_options_only');
function admin_area_for_manage_options_only() {

      if( defined('DOING_AJAX') && DOING_AJAX ) {
            //Allow ajax calls in order to have ALM working
            return;
      }

      if( ! current_user_can( "manage_options" ) ) {
           //Redirect to main page if the user has no "manage_options" capability
           wp_redirect( get_site_url( ) );
           exit();
      }
 }

Not sure why the above code is not working, is that the correct approach? Should I have introduced Apache re-direct rules in my .htaccess, instead?

4

2 回答 2

1

在你的functions.php中把这段代码

function redirect_non_admin_user(){
    if ( is_user_logged_in() ) {
        if ( !defined( 'DOING_AJAX' ) && !current_user_can('administrator') ){
            wp_redirect( site_url() );  exit;
        }
    }
}
add_action( 'admin_init', 'redirect_non_admin_user' );
于 2017-05-08T05:19:12.670 回答
1

将代码用作插件,主题功能对于某种动作/过滤器挂钩运行得很晚。

更好的是,只需将其添加为 mu-plugin,无需安装,无法通过管理面板禁用:https ://codex.wordpress.org/Must_Use_Plugins

<?php
/**
 * Plugin Name: Admin only for admins
 */

add_action( 'admin_init', function(){
      if( defined('DOING_AJAX') && DOING_AJAX ) {
            return;
      }    
      if( ! current_user_can( "manage_options" ) ) {
           wp_redirect( get_site_url( ) );
           exit();
      }
 });
于 2017-05-08T00:46:12.903 回答