1
votes

I am using the following code to create a shortcode and check for user role:

function check_user_role( $atts, $content = null ) {
        extract( shortcode_atts( array(
                'role' => 'role' ), $atts ) );

        if( current_user_can( $role ) ) {
                return $content;
        }
}
add_shortcode( 'user_role', 'check_user_role' );

and then adding the following shortcode to display the content only to the selected role - in this case 'subscriber'

[user_role role="subscriber"]content[/user_role]

it works great, but now I would like to add 'author' to the shortcode to display the content to both 'subscribers' and 'authors'

I've tried the obvious:

[user_role role="subscriber, author"]content[/user_role]

but that doesn't seem to be working.

Do I need to amend anything in the function it self?

2

2 Answers

3
votes

you have to just try it, for more help

https://wordpress.stackexchange.com/questions/131814/if-current-user-is-admin-or-editor

function check_user_role( $atts, $content = null ) {
        extract( shortcode_atts( array(
                'role' => 'role' ), $atts ) );

        $user = wp_get_current_user();
        $roles = explode(',', $user);
        $allowed_roles = array($roles);
        if( array_intersect($allowed_roles, $user->roles ) ) {
                return $content;
        }
}
add_shortcode( 'user_role', 'check_user_role' );
0
votes

For me, the code that worked was the following:

function check_user_role( $atts, $content = null ) {
        extract( shortcode_atts( array(
                'role' => 'role' ), $atts ) );

        $user = wp_get_current_user();
        $allowed_roles = explode(',', $role);
        if( array_intersect($allowed_roles, $user->roles ) ) {
                return $content;
        }
}
add_shortcode( 'user_role', 'check_user_role' );

I added this piece of code in a new Snippet in the Snippets plugin.