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.

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?

3 Answers
3

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();
    }
} 

Leave a Comment