Show part of the content only to logged in users or guests

Sometimes you need to show extra content only to users who are logged in to your site. Some other times, you will want to do the same for those who aren’t. So far, you have probably got accustomed to the fact that anything can be done in WordPress and you might have been searching for that option somewhere around the admin panel. Unfortunately, there is no one, but in this article, we will show you how to develop one.

While you can do the job by installing a plugin, this time we’ll show you a custom way. You will have to register shortcodes which you will use in your articles and show content only to logged in user or for those who aren’t logged in (guests).

To create both shortcodes, you will need to open your functions.php file and copy/paste the code:

Create a shortcode for logged in users:

add_shortcode('USER','show_user_content');
function show_user_content($atts,$content = null){
global $post;
if (!is_user_logged_in()){
return "You aren’t allowed to read this. " . wp_login_url( get_permalink($post->ID) ) . ' to view the content';
}
return $content;
}

Create a shortcode for guests:

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

After you have created the shortcodes, you’re ready to embed the content which will be shown only for logged in users or only for guests.

This is how it works:

  1. Add new post or edit an existing one
  2. Be sure you’re working in a Text Editor
  3. For logged in users, use [USERS] [/USERS] shortcode and write whatever you like in between. Logged in users will see the text you write between opening and closing shortcode tags, while guest will get a simple link which will lead them to login form.
  4. For users who aren’t logged in, use [GUEST] [/GUEST] shortcode

If you want to display more advanced content and show forms, galleries or anything else created by another plugin, you will probably need to copy/paste a shortcode created by that plugin. To make that work, you will need to replace the “return $content;” with “return do_shortcode($content);”.

That’s it. Go try your new shortcodes and we hope you will like them. If you’re going to use the shortcodes frequently, we suggest making a button containing them in your text editor.

START YOUR OWN BLOG

This guide is an introduction to mastering the art of blogging. It provides easy to follow steps to start, maintain, and grow your blog.

Read the guide

Leave a Reply

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