Force users to log in before reading specific posts

Most of your posts and pages will probably be opened to the public. Sometimes though, you will want to show specific posts only to your members. In this article, we’re about to show you how to force users to log in before showing them content for specific posts.

While you can use the WordPress feature and enter a password for specific posts, that means that a user somehow needs to get that password.  If you have more than a few members on your website, telling everyone a password might be a problem. So, if you want to let only members to view the post, you can force users to log in before they can open certain posts.

No, you won’t find the feature embedded into posts already, but you can easily create a function for yourself and choose posts which will be locked for everyone but those logged in.

Force users to log in for specific posts:

  1. Open functions.php file
  2. Copy and paste the following code:
  3. function force_post_login() {
    global $post;
    if (!is_single()) return;
    $ids = array(121, 235, 662, 777);
    if (in_array((int)$post->ID, $ids) && !is_user_logged_in()) {
    auth_redirect();
    }
    }
    
  4. Add post IDs in the array on the 6th line
  5. Save changes

After you have added posts’ IDs in the array, your posts are ready to be locked. But you still have to call newly created function somewhere in the post. You should do that from your header.php file:

  1. Open header.php
  2. Copy and paste this code on top of the file:
  3. <?php force_post_login(); ?>
  4. Save changes

Your new feature is now installed and ready to be used. While logged in users will normally browse through your site, those who aren’t logged in will be automatically redirected to the login page once they open a post with ID specified in the array in the code above. Simple as that.

Similarly, you can show part of the content only for logged in users.

START YOUR OWN BLOG

This guide is an introduction to mastering the art of blogging. It provides easy to follow steps to start, maintain, and grow your blog.

Read the guide

Leave a Reply

Your email address will not be published. Required fields are marked *