How to force all logged-out visitors in WordPress

Redirecting all logged-out visitors to your WordPress website to the homepage is very simple to achieve.

This can be achieved by simply adding a simple code to the functions.php file or using a plugin.

Follow the steps below to add the snippet to your theme’s function.php file:

Please ensure that you backup this file before pasting the code.

  • Login to the WordPress admin panel.
  • Click Appearance and then click Theme Editor.
  • Select functions.php on the list of files.
  • Add an action to the template_redirect hook with the following code:
//Redirect function
function not_loggedin_redirect() {
	//Check if page is not homepage or frontpage (to avoid too many redirect)
	if ( !is_front_page() && !is_home() ) {
	//Check if user is not logged-in (logged-out)
		if ( ! is_user_logged_in() ) {
		//Redirect to the home page
			wp_redirect( get_home_url() );
			exit;
		}
	 }
}
 //Fire action
 add_action('template_redirect','not_loggedin_redirect');
  • Save changes and test your website.

Leave a Reply

Your email address will not be published. Required fields are marked *