WordPress: Visitor depending content – Jocha

This tutorial will cover two methods for setting up shortcodes to use in your posts and pages that will allow you to hide or show content depending on who’s viewing it.

Content for users that are not logged in:

Many people want to focus on hiding content from this group of users, but you want to start by showing them content. Most traffic to your site will likely be through non-logged in users, so make sure you give this group of people something.

Open your theme’s functions.php file in your favorite text editor.

Add this PHP code:

add_shortcode( 'visitor', 'visitor_check_shortcode' );
function visitor_check_shortcode( $atts, $content = null ) {
if ( ( !is_user_logged_in() && !is_null( $content ) ) || is_feed() )
return $content;
return '';
}

Anytime you write a post/page, add this to only show content to users that are not logged in:

[visitor]
Some content for the people just browsing your site.
[/visitor]

You should also note that this content will be added to your feeds.

Showing content to logged-in users:

Now, you’ll see how to show content only to users that are logged into your site. This will be hidden from all other users and not shown in your feeds.

Add this code to your theme’s functions.php file:

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

Then, all you do is add some content in between your [member] tags when writing a post/page like so:

[member]
This is members-only content.
[/member]