0

I'm looking for a way to avid that some custom users roles are able to see wp-admin dashboard. I've found this topic and in my plugin class I've tried to use the two action suggested, but I will get an error about too few arguments passed.

This is my implementation of the code

    public function hide_dashboard_from_users( $user_login, $user )
    {
        if( !current_user_can('manage_options') && is_array($user->roles) && in_array('customer', $user->roles) ){
            wp_safe_redirect( site_url('/user-profile') );
        }elseif( !current_user_can('manage_options') && is_array($user->roles) && in_array('operator', $user->roles) ){
            wp_safe_redirect( site_url('/customers-manager') );
        }
    }

into the class construct I have these two actions

        add_action('wp_login', array($this, 'hide_dashboard_from_users'), 10, 2);
        add_action('admin_init', array($this, 'hide_dashboard_from_users'));

Why I will get the error and how I can fix it? Is there other actions or filter I can use to achive this?

2 Answers 2

1

The custom role needs the read capability to view the backend.

Example:

$your_role = get_role('your_custom_role');
$your_role->add_cap( 'read' );

See: https://wordpress.org/documentation/article/roles-and-capabilities/#read

Ideally, this should only be done once, e.g. when activating your plugin or theme.

1
  • Not sure to understand, The custom role already have the read permission when the plugin is activated, what I need is to avoid that this role can see the wp-admin dashboard, why I will need to set the read capability twice?
    – ICTDEV
    Oct 9, 2023 at 7:54
0

I've finally found a solution. I've used the admin_init action to redirect users that will have certain custom roles to the pages that they will need to see.

In a method of the plugin now I've this code

    public function hide_dashboard_from_users()
    {   
        $user = wp_get_current_user();

        if( !current_user_can('manage_options') && is_array($user->roles) && in_array('customer', $user->roles ) ){
            wp_safe_redirect( site_url('/user-profile') );
        }elseif( !current_user_can('manage_options') && is_array($user->roles) && in_array('operator', $user->roles) ){
            wp_safe_redirect( site_url('/customers-manager') );
        }
    }

And into the plugin class construct I've added this

add_action('admin_init', array($this, 'hide_dashboard_from_users'));

After some tests seems working fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.