Force Users To Login Before Reading Posts in WordPress

Wordpress-Force-Login-Screenshot-Plugin

Some WordPress CMS users might want to force users to Login before they read posts.
So we have h simple tutorial for them.
WordPress has a built-in function which can help you to do that.

The function 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 will be automatically 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 below 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 tf_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()) {
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(so it loads first and fast):
<?php tf_force_login(); ?>
The code is simple, but you can expand it with more options like: require login in some specific categories, make an option page for easy input post IDs, etc.
Its so simple isn't it .

Comments

Popular posts from this blog

Show Full Post on Front Page of Ghost, Not Excerpt

Video Blogger Templates

5 Beautiful Dark Blogger Templates