Redirect non logged in subscriber to different page when trying to access private page

Hi,

I have a set of nav buttons that appear only when the subscriber logs in, as they in a second menu that again only appears once the subscriber has logged in.

I have made the pages private and used the code below to allow the pages to work once the subscriber logs in.

 // Allow subscribers to see Private posts and pages

 $subRole = get_role( 'subscriber' ); 
 $subRole->add_cap( 'read_private_posts' );
 $subRole->add_cap( 'read_private_pages' );

Works fine as you know, but what I want to do is extend that code so that if someone tries to access those pages without being logged in they get re-directed to /sim-racing-registration/, so instead of seeing the Oops! page they get the opportunity to ‘Register’ or ‘Log in’.

Hello @multichild

You can accomplish a redirect to a certain page from another page for non-logged in users as such:

Place this code in your functions.php file in your theme

add_action( 'admin_init', 'redirect_non_logged_users' );

function redirect_non_logged_users() {
		if ( !is_user_logged_in() ) {
			wp_redirect( home_url( '/sim-racing-registration/' ) ); 
		exit;
	};
}

Then, place this code at the very top of any private template page that you do not want non-logged in users to view:

<?php redirect_non_logged_users(); ?>

When a user who is not logged in tries to visit your private pages, it will redirect them to the /sim-racing-registration/ page assuming that your page is located at http://yourwebsite.com/sim-racing-registration/ else, you will need to update the code above for your functions.php file to point to the correct page location.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.