Home > Mobile >  Display Current User Role in Woocommerce My account page
Display Current User Role in Woocommerce My account page

Time:05-25

I want to show the user role name with a shortcode on my custom account page. I found this code, but I couldn't use it because of my weak PHP.

add_action( 'wp_head', 'njengah_get_current_user_role'); 

function njengah_get_current_user_role() {

 if( is_user_logged_in() ) { // check if there is a logged in user 
 
         $user = wp_get_current_user(); // getting & setting the current user 
     $roles = ( array ) $user->roles; // obtaining the role 
 
        return $roles; // return the role for the current user 
 
     } else {
     
        return array(); // if there is no logged in user return empty array  
 
     }
}

Also, I found this, but I could not use it for the same reason: Display User Role Name on My Account Dashboard in WooCommerce

CodePudding user response:

The wp_head action hook is not used to print any data on the content area. It's triggered within the <head></head> section of the theme’s header.php template by the wp_head() function. So it won't print the value on your my-account page.

You should call the function directly within the custom my account page.

function njengah_get_current_user_role() {
     global $wp_roles;
     if( is_user_logged_in() ) {
        $user = wp_get_current_user();
        $roles = ( array ) $user->roles;
        $role = $roles[0]; 
        return translate_user_role($wp_roles->roles[$role]['name']);
     } else {
        return array();
     }
}

Then just call the function from your custom my account page.

echo njengah_get_current_user_role();
  • Related