First, your check code works, and takes this pattern:
if ( $current_user->data->wp_capabilities['hardcoded role name'] ) {
$role="hardcoded role name";
}
So lets swap the hardcoded role string out for a variable called $role_name
( you could call it something else if you want ). The check for a role name is now:
if ( $current_user->data->wp_capabilities[$role_name] ) {
$role = $role_name;
}
But we need to check more than one role, so, lets make a list of the roles to check
$roles_to_check = array(
'administrator',
'editor',
'author',
'contributor',
'subscriber'
);
Then check each role in our list
foreach ( $roles_to_check as $role_name ) {
.. do the check ..
}
So far everything we’ve done has been standard programming, with very little PHP specific knowledge. I recommend you take a good look at for loops and arrays as your question indicates a lack of knowledge or confidence in these areas.
But we’re not finished. You want to be able to handle any arbitrary role!
So lets start with get_editable_roles()
. This will give us an array of roles, but we can’t swap out the array from above without a slight modification.
$roles = get_editable_roles();
foreach ( $roles as $role_name => $role_info ) {
.. do our check ..
}
In your case however you want the roles of a specific user, so going back to your original check, you use this array:
$current_user->data->wp_capabilities
so if we do this for our loop:
foreach ( $current_user->data->wp_capabilities as $role_name => $capability ) {
You should be able to do what you desire