2

I want to learn how to create a WordPress shortcode that checks for a user role.

If a WP user has user role 'member1', then show the content. Otherwise, show nothing.

This is the WordPress code I have to check for a user role:

$user = wp_get_current_user();
if ( in_array( 'member1', (array) $user->roles ) ) {
    //The user has the "member1" role
}

I also know how to create a shortcode, like this:

add_shortcode( 'check-user-role', 'func_check_user_role' );
func_check_user_role() {

}

But how do I combine both into something that works like this (to check if a user has 'member1' user role:

[check-user-role='member1']show this content if the user has user role member1[/check-user-role]

Any suggestions?

2
  • This article in the Plugin Handbook could be helpful "Shortcodes with Parameters"
    – user141080
    Commented May 27, 2020 at 20:40
  • Thank you @user141080. Will read that!
    – Maurice
    Commented May 27, 2020 at 22:35

1 Answer 1

3

You can add a parameter to your shortcode function and use this value to check if the user is allowed to view the content:

function func_check_user_role( $atts, $content = null ) {
    $user = wp_get_current_user();
    $user_role = $atts['role'];
    $allowed_roles = [];
    array_push($allowed_roles , $user_role);

if ( is_user_logged_in() && array_intersect($allowed_roles, $user->roles ) ) {
      return $content;
 } else {
    return '';
}

}
add_shortcode( 'check-user-role', 'func_check_user_role' );

And your shortcode looks like:

[check-user-role role="subscriber"] Your content [/check-user-role]

So the $atts are your attributes, the $content is your post content.

Check out the documentation:

https://developer.wordpress.org/plugins/shortcodes/shortcodes-with-parameters/

You save the value inside of your $user_role variable and check, if your user is logged in and has the role which is inside of the user object (you got that in your $user). If this is true you return the content. If not true, there is nothing to be returned or maybe a string like "you are not allowed to view this content".

Hope this helps!

1
  • Awesome example rank! Thanks!!
    – Maurice
    Commented May 27, 2020 at 22:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.