Shortcode to Hide Content from Users that Aren’t Logged In

By mike on September 29, 2011 in Snippet
w0
k 0

A common issue many beginner WordPress users run into is blocking certain content from users that aren’t registered or logged in. Here is a short, simple solution in the form of a shortcode. Any content between the code block will only be output if the user has registered and logged in to their account.

You can paste this code into your functions.php to gain access to the WordPress shortcode.

add_shortcode( 'premium', 'mcp_premium_content' );

function mcp_premium_content( $atts, $content = null ) {
 if ( is_user_logged_in() && !is_null( $content ) && !is_feed() ){
  return $content;
 } else {
  return '';
 }
}

And now the following can be put into any post, page, or widgetized area to filter who sees your content.

[premium]**Any Content Here Can Only Be Viewed
By Registering and Logging In Users**[/premium]

This can be further refined by filtering by user types, but in this basic example I only checked if they had an account and were logged in.

0 Comments

Leave a reply

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>