Block site access for guests in WordPress with PHP

/**
 * Allows site access for logged-in users only.
 *
 * @see https://wpcodebook.com/block-site-access-guests-wordpress-php
 */
add_action( 'init', function () {
	if ( ! is_user_logged_in() ) {
		global $pagenow;
		if ( 'wp-login.php' !== $pagenow ) {
			wp_die( '<a href="' . wp_login_url() . '">' . esc_html__( 'Log in to access the site.' ) . '</a>' );
		}
	}
} );

Leave a Comment