As WordPress itself is very powerful concerning permission management, it’s sometimes a little bit difficult to perform very simple tasks. Recently I wanted to display different contents for different users (or more specifically: different user roles). However this isn’t possible to do out of the box.
There are a lot of plugins for managing user groups (or here) and even build big membership systems. But this seemed like a complete overkill for what I wanted to do. So I wrote a small shortcode that could do exactly that.
The usage is simple: an enclosing shortcode named [user_role] will take the attribute of role=”role“; the content between opening and closing shortcode brackets will only be shown to those users who have the appropriate role specified in the attribute.
1 2 3 4 5 6 7 |
[user_role role="administrator"] You can see this text if you are an administrator. [/user_role] [user_role role="subscriber"] You can read this if you are a common subscriber. [/user_role] Anyone can read this text. |
The user roles supported by WordPress by default are subscriber, contributor, author, editor and administrator. Of course you can expand this list by using various plugins (e.g. this one) and the shortcode will also work on those.
In order for the above shortcode to work, you will need to place the following PHP code in the functions.php of your current theme (you can do this of course via SSH, FTP or in the WordPress administrator backend editor):
1 2 3 4 5 6 7 8 9 10 11 12 |
/* print content of enclosing shortcode if user is of role attribute */ function check_user_role( $atts, $content = null ) { extract( shortcode_atts( array( 'role' => 'role' ), $atts ) ); if( current_user_can( $role ) ) { return $content; } } /* register shortcode handler function */ add_shortcode( 'user_role', 'check_user_role' ); |
Again, this was meant to perform just a simple task, that’s why it was done as a featureless and minimalistic piece of coding.
One of the features that could be added next would be the possibility to use a list of user roles as attribute, because at this stage, you have to write one shortcode for each user role you would like to read the content (even if it’s the same for different user roles).
Thanks man! Works nicely
Thank you! It works!