Custom role based users are not able to access wp-admin

First of all I am a WordPress learner. So sorry if my code looks stupid!

I have created a custom theme with a custom user role. I am not developing any plugin.

In my fucntions.php file I have written the following code to create a User role. Users assigned to this role are supposed to login to the admin but only be able to access their Profile pages.

add_action('init', 'yrc_cst_register_role_customer_service_rep');

/**
 * Register new user role
 */

function yrc_cst_register_role_customer_service_rep() {

    $wp_roles = new WP_Roles();

    $wp_roles->remove_role('subscriber');
    $wp_roles->remove_role('editor');
    $wp_roles->remove_role('contributor');
    $wp_roles->remove_role('author');

    $service_rep_caps = array(
        'read'              => false,
        'create_posts'      => false,
        'edit_posts'        => false,
        'edit_others_posts' => false,
        'publish_posts'     => false,
        'manage_categories' => false,
        'manage_options'    => false,
    );

    add_role('customer_service', __('Customer Service'), $service_rep_caps);
}

I have removed all roles except Administrator, because no other role is required for this portal. Administrator will only create Users with Customer Service role.

I have no third party plugin installed in the system.

Users with the custom role are able to login to the system through a custom login page which is working OK. But whenever they are trying to access their Profile page the following error message comes up:

Sorry, you are not allowed to access this page.

Is there anything like 'edit_profile' => true?

I must be doing something wrong but my limited knowledge is not enough to figure this out. Any suggestion would be highly appreciated.

1 Answer
1

The read capability must be set to true, so they can access.

Keep in mind, roles are saved to the database, when you run it on every init action, this is considered to be time consuming.

The Codex suggests to run those actions in the register_activation_hook(). Since you are using this code in your theme, you might want to check, if the role exists.

Since you are running this in a theme, this might be a workaround:

function yrc_cst_register_role_customer_service_rep() {

    $wp_roles = new WP_Roles();

    //$wp_roles->remove_role('customer_service'); // Remove it only for test purposes.

    if ( $wp_roles->is_role( 'customer_service' ) ) {
        return;
    }

    $wp_roles->remove_role('subscriber');
    $wp_roles->remove_role('editor');
    $wp_roles->remove_role('contributor');
    $wp_roles->remove_role('author');


    $service_rep_caps = array(
        'read'  => true,
    );
    add_role('customer_service', __('Customer Service'), $service_rep_caps);

}

Leave a Comment