Search code examples
phpwordpress

WordPress filters - Filter to control which page is being loaded


I am trying to develop an password role protection on my web. What I need to achieve is to redirect visitors to the login wp-login.php when they try to enter an specific page if they are Suscribers. WordPress doesn't give us that option so I had to develop myself (I don't want to use external plugins).

I had the role filter, but I can't find the filter to control which page is being loaded in order to redirect the visitor.


Solution

  • Add this code in your Function.php file. using template_redirect action hook

    This action hook executes just before WordPress determines which template page to load. It is a good hook to use if you need to do a redirect with full knowledge of the content that has been queried.

    function template_redirect_fn()
    {
        //add you logic to perform your task  
        //Redirect page to login page 
        if(is_page ('about-us'))
        {
    
            $loginUrl = "LOGIN URL";
            wp_redirect($loginUrl);
             exit(); 
        }
        //if more then one page then used this 
    
        if( is_page( array( 'about-us', 'contact', 'management' ) )
          // about us, or contact, or management page is in view
    
    }
    add_action( 'template_redirect', 'template_redirect_fn' );
    

    is_page(Page ID OR title OR slug of you want to check )