How to check user role?

I have functions that have to execute based on the user roles. How do I check the user role so that I can insert the respective function under their role?

EG.

Read More
if ($_GET['role'] == "free member" ) {//insert funtion 1}

elseif  if ($_GET['role'] == "sliver member" ) {//insert funtion 2}

else {//insert funtion 3}

I tried using current_user_can, like this :

global $get_currentuserinfo, $current_user; 
if( current_user_can('free_member') ) {//insert funtion 1} 
elseif current_user_can('sliver_member'){//insert funtion 2} 
else {//insert funtion 3} 

This work with default role like “editor”,”author”, “contributor”. but seem doesn’t work with custom role that created by role managing plugin. I am using Advanced Access Manager to create the custom role by the way.

Since this role checking snippet is using in writing panel, so what approach is best to check the user role?

Related posts

Leave a Reply

1 comment

  1. Looking around Google for a few minutes yielded several promising results.

    Here’s a more detailed one adapted from a snippet on The Code Collective:

    function get_user_roles( $user_id ) {
        $user_roles = [];
    
        $user = get_userdata( $user_id );
        $capabilities = $user->{$wpdb->prefix . 'capabilities'};
    
        if ( !isset( $wp_roles ) ) {
            $wp_roles = new WP_Roles();
    
            foreach ( $wp_roles->role_names as $role => $name ) {
    
                if ( array_key_exists( $role, $capabilities ) )
                    $user_roles[] = $role;
            }
        }
    
        return $user_roles;
    }
    

    This will return an array of the user passed in as $user_id.