WordPress Tip: Show page content only to logged in users

Here’s a quick spell for today for showing WordPress page or post content only to logged in users. The code below can be used on your page template to hide any part of the page. In this quick tutorial we will use this code to show a message to users who are not authenticated and show the post or page content to those who have been authenticated.

First we open single.php (assuming we will be restricting content access on single posts) and locate the following:

<?php the_content(); ?>

Comment that code and replace by the following:

<?php if (is_user_logged_in()) { the_content(); } else { echo "Please register or login to view this section."; } ?>

That’s it. We have basically used a simple if/else statement here along with the WordPress function is_user_logged_in which is defined in WP itself to accomplish this step.

Some other cool usage can be:

  1. Use it to show ads only to un-authenticated users
  2. Display comment section only to authenticated users
  3. Put conditional events for running of other functions based on authentication

Don’t forget to share this tip if you find it useful.

Divi WordPress Theme

Leave a Reply

Be the First to Comment!

Leave a Reply


wpDiscuz