22-Jan-2013 : Protected content

  • by

This little PHP snippet allows you to selectively display content to users based on whether or not they’re logged in.  For example, a casual visitor who’s not logged in might be greeted with “Welcome to my Web site… please consider becoming a registered user”, whilst someone who’s logged in might see Welcome… thank you for taking the time to register and log in”.  It can also be used to hide content which you don’t want to be seen by visitors who aren’t logged in, and since it’s executed on the server as the page is built, it’s not detectable merely by viewing the page’s source HTML.  Very useful!

Make sure you know where your theme’s functions.php file is stored: it will be somewhere like /public_html/wp/wp-content/themes/theme_name/functions. Make sure you know how to replace this file manually, either via your site’s cPanel or by ftp.

Go Appearance > Editor and select functions.php. Before you go any further, make a backup of this file by copying & pasting the contents into a text file somewhere on your computer. If you make a mistake and your site refuses to load, you will have to restore it.

Scroll to the bottom of the file and identify the last curly bracket ‘}‘ and the PHP close tag ‘?>‘, then paste the following code after the }‘ and before the ?>:-

    // enable/disable content if logged in/out
  
   function if_logged_in( $at, $content = null ) {
        if ( is_user_logged_in() && !is_null( $content ) && !is_feed() )
           { return $content; }
        else
             { return ”; }
        }
    add_shortcode( ‘logged_in’, ‘if_logged_in’ ); 
 
  function if_logged_out( $at, $content = null ) {
        if ( is_user_logged_in() && !is_null( $content ) && !is_feed() )
            { return ”; }
        else
            { return $content; }
       }
    add_shortcode( ‘logged_out’, ‘if_logged_out’ );

The bit in green is a comment: change this to suit.

Click Update File.

To protect content from being seen by users who aren’t logged in, wrap it in [logged_in] & [/logged_in] shortcodes. To display content only to users who aren’t logged in, wrap it in [logged_out] & [/logged_out] shortcodes. Here’s an example:-

[logged_in]You’re seeing this content because you’re logged in. If you log out, it will no longer be visible to you.[/logged_in]
 
[logged_out]There is protected content on this page. You must log in if you wish to see it.[/logged_out]

Notes:-

(i) Your editor may not give you access to the functions.php file from the WordPress dashboard, If this is the case, you will need to edit it via cPanel, or download it via ftp, edit it locally, then re-upload it.

(ii) The functions.php file will probably be replaced if you update or reinstall WordPress or your chosen theme. If this happens, you will need to re-apply this patch.