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:
- Add this code to your theme’s functions.php file or in a site-specific plugin.
- 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.
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 ''; }
[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