Family Encyclopedia >> Electronics

Force users to login before reading posts in WordPress

If your blog has a restricted area that you don't want to disclose to all visitors, members only, you may want to force users to log in before reading these posts . Fortunately, WordPress has a built-in feature that can help us do this.

Force users to login before reading posts in WordPress

The function is auth_redirect(), here's how it works:when called from a page, it checks 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 login they will be Sent directly to the page they were originally trying to access. .

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

Simply paste the following code into your theme functions.php file:

 function my_force_login () global $ post; if (! is_single ()) return; $ ids = array (188, 185, 171); // conjunto de ID de publicación que obligan a iniciar sesión para leer if (in_array ((int) $ post-> ID, $ ids) &&! is_user_logged_in ()) auth_redirect (); 

Change the Post ID array to suit your needs. After that, open the header.php file and put the following code at the top:

 

The code is simple, but you can Expand it with more options like:require login in some specific categories, create an options page to easily enter login IDs, etc.

The auth_redirect() function is available since WordPress 1.5.

Force users to login before reading posts in WordPressTuan Anh (aka Rilwis) is a 25-year-old blogger and web developer from Vietnam. He is interested in PHP, MySQL and Web 2.0 technologies (CSS, Javascript, Ajax). He loves WordPress and everything related to it. Follow Rilwis on Twitter To keep up with him. The Rilwis Website:Luxury Blog Tips