Force Users To Login Before Reading Posts in WordPress

Posted on January 29th, 2011

If there is any restricted area in the blog which can be only publicized to the members , force users to login before reading these posts is used. WordPress has a built-in function which can help us to do that.

The function is auth_redirect(), this is how it works: When this function 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. The user is redirected in such a way that, upon logging in, they will be sent directly to the page they were originally trying to access.

By using this function, we can implement our code that check if post is restricted or not, and redirect users to login page if needed.

Just paste the following code into your theme’s functions.php file:

function my_force_login() {
global $post;

if (!is_single()) return;

$ids = array(188, 185, 171); // array of post IDs that force login to read

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