Proper method to restrict non logged users into certain pages

I was wondering which is the correct method to do this and which action hook should i use.

I have custom login/register pages so if the user try to go to a forbidden page and its not logged in i will redirect him to a login page.

Read More

Currently on my functions.php i got the following:

/*
*   Restrict non logged users to certain pages
*/

add_action('template_redirect','my_non_logged_redirect');
function my_non_logged_redirect()
{
     if ((is_page('mi-perfil') || is_page('agregar-empresa')) && !is_user_logged_in() )
    {
        wp_redirect( home_url() );
        die();
    }
}   

Im using the right method/hook or should i use another one or a easier one?

Related posts

Leave a Reply

4 comments

  1. I couldnt find a better method other than:

    /*
    *   Restrict non logged users to certain pages
    */
    
    add_action('template_redirect','my_non_logged_redirect');
    function my_non_logged_redirect()
    {
         if ((is_page('mi-perfil') || is_page('agregar-empresa')) && !is_user_logged_in() )
        {
            wp_redirect( home_url() );
            die();
        }
    } 
    
  2. I just want to say thanks, I was able to use this and do exactly what I hoped changing the line to cover the category and sending people to my login page instead of the home url,

    /*
    *   Restrict non logged users to certain pages
    */
    
    add_action('template_redirect','my_non_logged_redirect');
    function my_non_logged_redirect()
    {
         if ((in_category(1) && !is_user_logged_in() ))
        {
            wp_redirect( 'http://mysites.com/loginpage/' );
            die();
        }
    }
    
  3. The posts/pages which you want to hide from non logged in users can be published as “Private” and it will not be available to any public visitor of the site. This way you don’t need to implement any sort of redirection or custom code.
    You can find more information here.

  4. I know this post is almost a decade now, but I will just put it out there since I found it useful.

     /*
    *   Restrict logged-out users from privileged pages
    */
    
    add_action('template_redirect','rex_non_logged-in_redirect');
    function rex_non_logged-in_redirect()
    {
         if ((is_page('/*page id to be restricted*/') || is_page('/*page id to be restricted*/')) && !is_user_logged_in() ) /* Checks page(s) you want to restrict from logged-out users and also check if user is logged in*/
        {
            wp_redirect( 'enter the full url of your login page' );
            die();
        }
    } 
    

    This is a leaf from what the guys have posted previously. Just wrapping it up together. I hope this helps anyone needing it.