Paulund
2014-06-11 #wordpress

Display Content For Registered Only Users In WordPress

The registered users of your website are the most valuable visitors you can get on your website, these people are loyal visitors and you should reward them for that. One of the best ways of rewarding your registered users is with new premium content, which can be reserved just for the visitors who are logged in. The following code snippet will allow you to place content which is only available for the users that have logged into your website, we will then use a shortcode to show the difference between normal content and premium content just for logged in users. The following code snippet will first check to see if the user is logged in, this check is done by a WordPress function is_user_logged_in(). Then we need to check that the content is not empty, we also need to check that the content is not currently being displayed on the RSS feed. Simply add the following code in your plugin or functions.php file to register a new shortcode called members_only.


add_shortcode( 'members_only', 'members_only_shortcode' );
function members_only_shortcode( $atts, $content = null ) 
{
    if ( is_user_logged_in() && !empty( $content ) && !is_feed() )
    {
        return $content;
    }
    
    return 'To view this content please login.';
}

Now that a shortcode has been registered you can use this in the content area just like the code below.


[members_only]
Display this content only for users which are logged in.
[/members_only]

Please note that this solution will only be acceptable if admin user of the site does not remove the theme or plugin where this shortcode function exists. If they remove the plugin or theme then all the content inside this shortcode will be available for everyone to see.