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;
/* 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();
}
}
});
$url
, or try something likewp_redirect( home_url( '/my-account/' ) );
? – Sally CJ Commented Mar 3, 2023 at 1:32