Search code examples
wordpress.htaccesswp-admin

How do I re-direct non admin and end users to home when hitting wp-admin


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?


Solution

  • Use the code as a plugin, the theme functions run very late for some kind of action/filter hooks.

    Even better, just add it as a mu-plugin, no need to install, impossible to disable via admin panel: 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();
          }
     });