Redirect non-logged in users to a specific page

admin2025-01-08  5

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 (/)

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;

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;
Share Improve this question edited Mar 3, 2023 at 1:23 YourManDan 4342 silver badges12 bronze badges asked Mar 2, 2023 at 11:27 RobRob 1 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
Add a comment  | 

1 Answer 1

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

}

});

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736269730a1374.html

最新回复(0)