How to Show or Hide Content in WordPress / WPMU Based on User Authentication, Roles, and Capabilities

How to Show or Hide Content in WordPress / WPMU Based on User Authentication, Roles, and Capabilities

Here is a handy little code snippet that falls into the basic category for WordPress but can prove to be extremely useful when customizing your installation. Whether you’re working with WordPress, WPMU or BuddyPress, these little tips will give you greater flexibility in building your community.

{code type=php}<?php if (is_user_logged_in() ) { //only logged in user can see this ?>

I love green tea!

<?php } ?>

You can also selectively show content using role-based permissions, as detailed in the WordPress codex section on roles and capabilities. For example, if you want to show a specific menu to your admins and editors only but show a different menu for everyone else, you can do something like this:

{code type=php}<?php if ( current_user_can( ‘delete_others_posts’ ) ) { //only admins and editors can see this ?>

  • Secret Menu Item
  • Other Restricted Link

<?php } else { ?>

  • General Menu
  • Anyone Can See This

<?php } ?>

These is a starting point so that you can write your own.There are some plugins which accomplish these things. However, sometimes you cannot find a plugin specific enough to do what you need and you only want it applied in one area. That’s when these quick snippets will come in handy.

Other possible uses might include:

  • Hide signup information from logged-in users and re-appropriate that space on the page targeted to your subscribers.
  • Sell and display ads targeted to your casual visitors or to your registered users.
  • Show or hide widgetized areas in your sidebar based on if the user is logged in or not.
  • Display alternate footers, sidebars, headers, page elements, etc. instead of having to create a custom template for each instance.
  • Reserve certain content for registered users only, ie “Members only downloads” or restricted galleries.
  • Attach it to your “Read More” links to get users hooked before requiring registration.
  • Create a separate menu bar for your clients for payment forms for registered users, etc.
  • If you’re using BuddyPress, you could tweak it to selectively target profile areas to be private unless the user is logged in.

If you use your imagination, I’m sure that you can find unlimited ways to show and hide content. In this age of social networking, users’ attention spans are decreasing and they will often click away from sites that instantly offer too much cluttered information. One of the most important reasons to show and hide information based on a user’s role is to conserve the real estate on the page and strategically target the information on your site to registered or non-registered users. These simple snippets are a good foundation for how to use BuddyPress conditional tags, for which we will provide an introduction next week. Stay tuned!