Checking for user role in a custom plugin

Why it doesn’t work for a Plugin:

It doesn’t work for plugin because by the time WordPress executes $current_user = wp_get_current_user(); in a plugin, the function wp_get_current_user() isn’t defined yet. WordPress loads that plugin file before it defines those user related functions. However, it works for theme because WordPress loads theme after it defines and initiates those user centric functions.

How to make it work in a plugin:

For it to work in a plugin, you may use an action hook. For example, it’ll work after plugins_loaded action hook is fired. Like the CODE below:

add_action( 'plugins_loaded', 'check_current_user' );
function check_current_user() {
    // Your CODE with user data
    $current_user = wp_get_current_user();
    
    // Your CODE with user capability check
    if ( current_user_can('wholesale_customer') ) { 
        // Your CODE
    }
}

With the above CODE you’ll see checking role with current_user_can() and getting user information with wp_get_current_user() works inside a plugin.