I Design + Develop + Support WordPress websites

Display Content Only to Logged in Users in WordPress

This is something I recently did for one of my sites that I think is really neat, so hopefully you will find it useful as well.

Basically it adds content to a post or page based on your input in a custom field, but only for logged in users. It also displays a message telling non-logged-in users that they’re missing out on something.

Here’s the first part of the code which goes in your themes functions.php (custom_functions.php if you’re using Thesis):

function add_loggedin_content () {
global $post;
$loggedinmessage=get_post_meta($post->ID, 'logged_in_content', TRUE);
if ($loggedinmessage) {
if ( is_user_logged_in() ) {
echo do_shortcode( $loggedinmessage );
else {
echo 'This page contains content that only logged in users can view. If you are registered <a href="/wp-login.php">click here</a> to get access. To register <a href="/wp-login.php?action=register">click here</a>.';

My application is to display a contact form only to logged in users. Since I’m using contact form 7, I wanted to be able to insert a shortcode in the custom field. If you wanted to insert regular content just change:
echo do_shortcode( $loggedinmessage );
echo $loggedinmessage;

Adding the user only content

To use this function just go to the post/page, scroll down to “Custom Fields” and click on “Enter New.” In the “name” field enter:

Then enter whatever shortcode or content you want in the “Value” field.

Theme specific code

You need to add a bit more code to get the contents of your new custom field to actually show up. The problem is that this code tends to be theme specific.

The site I’m using this code on is using the Thesis Theme. If you are too you can just use this code:

add_action('thesis_hook_after_post', 'add_loggedin_content');

This will run the function at the bottom of the post.

To get the code to a similar location in the Genesis Theme, another of my favorites you’d instead use:

add_action('genesis_after_post_content', 'add_loggedin_content');

Please note that I haven’t actually tested this, but according to WPrecipes you should be able to get a similar effect in any wordpress theme by instead using this code:

add_filter('the_content', 'add_loggedin_content');

So what uses can you think of to put this code to use for?

Speak Your Mind