X

How To Display Content Based on the User’s Capabilities

Snippets by IsItWP

Are you looking for a way to display content based on the user’s capabilities? This snippet will let you show or hide content based on the capabilities of the current user.

Instructions:

  1. Add this code to your theme’s functions.php file or in a site-specific plugin.
  2. add_shortcode( 'access', 'access_check_shortcode' );
    function access_check_shortcode( $attr, $content = null ) {
    	extract( shortcode_atts( array( 'capability' => 'read' ), $attr ) );
    	if ( current_user_can( $capability ) && !is_null( $content ) && !is_feed() )
    		return $content;
    	return '';
    }
    
  3. Use this shortcode in your posts to hide content. Edit the shortcode content and set the capability type to suit your needs. View the codex for more information on user roles and capabilities.
  4. [access capability="switch_themes"]
    The currently logged-in user can see this sentence.
    [/access]
    

This snippet was created by Justin Tadlock.

Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly copy / paste code snippets in WordPress, so you don’t accidentally break your site.

If you liked this code snippet, please consider checking out our other articles on the site like: 6 Best WordPress Security Plugins Compared and how to set up Shopify with WordPress.

Comments   Leave a Reply

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!