Latest blog posts

header ads

check user role and add class his role base on body using php

To add a class to the body element based on the user's role in WordPress, you can use PHP to dynamically generate the class name and then output it in the HTML. Here's how you can do it: Retrieve User Role: Use WordPress functions to retrieve the current user's role. Output Class in HTML: Output the class in the HTML body tag. Here's the PHP code you can place in your theme's functions.php file or a custom plugin:

roles; // Get the highest priority role (last role in the array) $user_role = end($user_roles); // Sanitize the role name to make it suitable as a class name $sanitized_role = sanitize_html_class($user_role); // Output the class in the body tag echo ''; } } add_action('wp_footer', 'add_role_based_class_to_body'); ?>

In this code: We retrieve the current user's roles using wp_get_current_user(). We extract the last role in the array (assuming roles are in order of priority). We sanitize the role name using sanitize_html_class() to ensure it's safe to use as a class name. We then output a JavaScript snippet that adds a class to the body element based on the user's role. Finally, you can add CSS styles for each user role in your theme's CSS file:

/* Define styles for different user roles */ .user-role-admin { /* Add styles for admin users */ } .user-role-editor { /* Add styles for editor users */ } /* Add styles for other user roles as needed */

This way, each user role will have its own set of styles applied to the body element based on the dynamically generated class.

Post a Comment

0 Comments