Lock content

Show Content to user or guest only

I just got the same question in the mail for about the 10th time in many forms :

How can i show content to guests only?
How can i show content to users only?
How can i Lock content for members only?
WWhat is the shortcode for logged in and logged out?

Well there is no built in native WordPress Function or Shortcode to do that but there are some very simple tools to help with that and in tools i mean the is_user_logged_in() and the shortcode API.

So here we go, First we create a shortcode to handle content meant for users only:

add_shortcode('USER','show_user_content');
function show_user_content($atts,$content = null){
	global $post;
	if (!is_user_logged_in()){
		return "this is for looged in users only  " . wp_login_url( get_permalink($post->ID) ) . ' to view the content' ;
	}
	return $content;
}

What this snippet does is it create a new shortcode [USER] which will only show the enclosed content to logged in users and if its a guest it will show him a link to the login form.

Next we want to add a shortcode that will show content just for guests so:

add_shortcode('GUEST','show_guest_content');
function show_guest_content($atts,$content){
	if (!is_user_logged_in()){
		return $content;
	}
        return '';
}

And This simple snippet adds another shortcode [GUEST] which will show enclosed content only to guests.

Usage:

[GUEST]
this content for the people just browsing your site
[/GUEST]
[USER]
 this is the premium content (this is only shown to logged in users)
[/USER]

Short and simple, and all you have to do is paste the snippets in your functions.php or create a plugin file for it and you are set to use these shortcodes as much as you want.
For more advanced content locking and limiting per specific user by name, role or id take a look at my User specific Content Plugin.

Ohad Raz

WordPress Consultant, a WordPress Developer and a WordPress Freelancer With over 10 years experience in architecting web sites and applications. WordPress Development moderator and somethimes Plugin Developer.