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?

brasofilo
  • 23,940
  • 15
  • 86
  • 168
paranza
  • 1,281
  • 5
  • 27
  • 54

2 Answers2

1

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();
      }
 });
brasofilo
  • 23,940
  • 15
  • 86
  • 168
1

in your functions.php put this code

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' );
Exprator
  • 23,516
  • 5
  • 33
  • 47