This article has been modified and simplified to let a better experience with the subject.
HeelpBook© Staff
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.
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; if (is_single() && !is_user_logged_in()) { auth_redirect(); } }
After that, open the header.php
file and put the following code in the very top:
<?php my_force_login(); ?>
The code is simple, but you can expand it with more options like: require login in some specific categories, etc.
The function auth_redirect() is available since WordPress 1.5.
SOURCE | LINK | LANGUAGE | ENGLISH |