Force Users To Login Before Reading Posts in WordPress




If your blog has some restricted area that you don’t want to publicize to all visitors, just for members only, then you might want to force users to login before reading these posts. Fortunately, WordPress has a built-in function which can help us to do that.

The function is auth_redirect(), this is how it works: When it is called from a page, it checks to see if the user viewing the page is logged in. If the user is not logged in, they are redirected to the login page.

Sample code, add the code in your functions.php file

function my_force_login() {
 global $post;

 if (!is_single()) return;

 $ids = array(100, 101, 102);  

 if (in_array((int)$post->ID, $ids) && !is_user_logged_in()) {
  auth_redirect();
 }
} 

Change the array of post IDs to fit your requirement. After that, open the header.php file and put the following code in the very top:

<?php my_force_login(); ?>

Reference: Github, Wordpress.org



Related Post


Latest Post


Recent Posts Widget

Make sure to never miss a thing...

Get the latest news from the creative industry along with other creative goodies, conveniently delivered to social media.