0

I am trying to find a way to restrict access to two specific pages to logged in users only.

Currently we are using the code below to show a non-logged in user a blank screen with the message "You are not allowed to access this page" however rather than showing this we want to redirect them to the login page (https://craftyquiz.com/my-account/)

Is there a way to do this?

if( !function_exists('tf_restrict_access_without_login') ):
 
    add_action( 'template_redirect', 'tf_restrict_access_without_login' );
 
    function tf_restrict_access_without_login(){
         
        /* get current page or post ID */
        $page_id = get_queried_object_id();
 
        /* add lists of page or post IDs for restriction */
        $behind_login_pages = [ 58875 ];
 
        if( ( !empty($behind_login_pages) && in_array($page_id, $behind_login_pages) ) && !is_user_logged_in() ):
 
            wp_redirect( $url );
            exit;
 
        endif;
    }
 
endif;
2
  • Your code is already attempting to do the redirect. You just need to define the $url, or try something like wp_redirect( home_url( '/my-account/' ) ); ?
    – Sally CJ
    Commented Mar 3, 2023 at 1:32
  • 1
    This worked perfectly! Thank you so much for your help, I really appreciate it.
    – Rob
    Commented Mar 6, 2023 at 13:07

1 Answer 1

0
/* add code in current theme activate in this file functions.php */
add_action( 'template_redirect', function() {

if( ( !is_page('login') ) ) {

    if (!is_user_logged_in() ) {
        wp_redirect( site_url( '/login' ) );        // Example : login page             
        exit();
    }

}

});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.