This page provides a tweak to automatically redirect non-members to the login page upon visiting your site.
This type of customization is useful for globally protecting your site, ensuring only logged-in members can access various pages. Any non-members will be automatically redirected to the login page.
If you have PHP coding knowledge, you can further modify this example to automatically redirect any non-members who try to access a protected post or page.
Note/Warning: Custom PHP coding can break your site. So custom PHP code should only be used if you are familiar with PHP coding.
Add the following PHP code to your theme’s functions.php file or a custom plugin:
/*** Auto redirect a user who isn't logged into the site ***/
add_filter( 'pre_get_posts', 'swpm_auto_redirect_non_members' );
function swpm_auto_redirect_non_members() {
if (is_admin()){
//Inside the admin dashboard. Nothing to do.
return;
}
//We are on the front-end. Lets check visitor's login status.
if( !SwpmMemberUtils::is_member_logged_in() && !is_page( array( 'membership-login', 'membership-join' )) ) {
wp_redirect( 'https://www.your-domain.com/membership-login' );
exit;
}
}
You will need to change the redirection URL to the actual login page URL of your site.
The non logged-in users are only allowed to access the membership login and join us pages in the above example.
Note: If you need help with custom coding, you may need to hire a WordPress developer or our developer. Custom coding help is beyond the scope of our free support. You can contact us if you want to hire our developer for custom coding or customization work for your site.