Archived topic
Conditional tag for user role?
6 replies · Started by Carsten on January 21, 2023
Hi there, I'm looking for away to make a conditional tag for user roles and have been looking through the WP Conditional Tags Codex without finding anything about user roles.
What I'm trying to achieve is to display this shortcode for customers
add_action( 'bp_after_member_profile_content', 'konkurrence_shortcode' );
function konkurrence_shortcode() {
echo do_shortcode( '[nfpd_entry_page]' );
}
I have been trying with if ( is_customer() ) and if(current_user_is("customer")) without luck.
Why is user roles not on the conditional tags list, is this not possible?
Thanks
Hi there,
Wordpress haas the wp_get_current_user() function:
https://developer.wordpress.org/reference/functions/wp_get_current_user/
And that includes the roles array which you can check for your specific role.
Example code to check us user has a role of customer:
$user = wp_get_current_user();
if ( in_array( 'customer', (array) $user->roles ) ) {
//The user has the "customer" role
}
Does this help?
$user = wp_get_current_user();
if ( in_array( 'shop_manager', (array) $user->roles ) ) { // user role condition
echo do_shortcode('[gravityform id="2"]');
}
Yes, it's working very well now, thank you both ;-)
One question, I'm trying to add two user roles to the code, I have tested it in php checker, with no issues found, but when i insert it in the code, the site breaks
add_action( 'bp_after_member_profile_content', 'konkurrence_shortcode' );
function konkurrence_shortcode() {
$user = wp_get_current_user();
if ( in_array( 'contributor','subscriber', (array) $user->roles ) ) { // user role condition
echo do_shortcode( '[nfpd_entry_page]' );
}
}
Try this:
add_action( 'bp_after_member_profile_content', 'konkurrence_shortcode' );
function konkurrence_shortcode() {
$user = wp_get_current_user();
if ( in_array( 'contributor', (array) $user->roles ) || in_array( 'subscriber', (array) $user->roles )) {
echo do_shortcode( '[nfpd_entry_page]' );
}
}
Thanks Ying ;-)
No Problem :)