Site logo

[Resolved] Conditional tag for user role?

Home Forums Support [Resolved] Conditional tag for user role?

Home Forums Support Conditional tag for user role?

Viewing 7 posts - 1 through 7 (of 7 total)
  • Author
    Posts
  • #2504341
    Carsten

    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

    #2504746
    David
    Staff
    Customer Support

    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
    }
    #2505217
    Scott

    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"]');
    }
    #2506133
    Carsten

    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]' );
    }
    }
    #2506304
    Ying
    Staff
    Customer Support

    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]' );
        }
    }
    #2506326
    Carsten

    Thanks Ying 😉

    #2506335
    Ying
    Staff
    Customer Support

    No Problem 🙂

Viewing 7 posts - 1 through 7 (of 7 total)
  • You must be logged in to reply to this topic.