John Davidson

PHP Wordpress Look up user-role for logged in user, add to page class

0 comments
Message:


Wordpress PHP:
I am in need of a small php script that allows me to check for the userrole of the active logged in user. And to output it as a class item.


I have assigned User Roles via Ultimate Member - if that has anything to say.


Example:
A user is a member of a role, named: "storeowner".
I would like to add that to a div as a shortcode of sorts.


Is there a quick and dirty solution out there ?
Sorry if this has been asked and answered, but I haven't been able to find it.



My Answer:
"subscriber". I want to add a class to the body tag of the page that says "subscriber" if the logged in user is a subscriber.

Here is a PHP script that you can use to achieve this:

php
// Check if user is logged in
if ( is_user_logged_in() ) {
// Get the current user object
$current_user = wp_get_current_user();

// Get the user role
$user_roles = $current_user->roles;

// Check if user has the role "subscriber"
if ( in_array( 'subscriber', $user_roles ) ) {
// Add class to body tag
add_filter( 'body_class', function( $classes ) {
$classes[] = 'subscriber';
return $classes;
});
}
}
?>


You can add this script to your theme's functions.php file or create a custom plugin for it. This script will check if the user is logged in, get their user role, and add a class to the body tag if the user has the role "subscriber".

Rate this post

5 of 5 based on 3680 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us