Home / Allow Only Logged-In Users
Duplicate Snippet

Embed Snippet on Your Site

Allow Only Logged-In Users

Make your site private just for logged-in users.

200+
Code Preview
php
<?php
add_action(
	'wp',
	static function () {
		if ( is_user_logged_in() ) {
			return;
		}
		// Handle API requests separately.
		if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
			return;
		}
		// Allow access to the login screens.
		$allowed = array(
			'wp-login.php'     => true,
			'wp-signup.php'    => true,
			'wp-activate.php'  => true,
			'wp-trackback.php' => true,
			'wp-cron.php'      => true,
		);
		if ( isset( $allowed[ basename( $_SERVER['PHP_SELF'] ) ] ) ) {
			return;
		}
		nocache_headers();
		wp_safe_redirect(
			wp_login_url(
				set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] )
			)
		);
		exit;
	}
);
// Custom Login error.
add_action(
	'init',
	static function () {
		global $error;
		if ( 'wp-login.php' !== basename( $_SERVER['PHP_SELF'] ) || ! empty( $_POST ) || ( ! empty( $_GET ) && empty( $_GET['redirect_to'] ) ) ) {
			return;
		}
		$redirect = isset( $_GET['redirect_to'] ) ? $_GET['redirect_to'] : '';
		if ( ! $redirect || str_starts_with( $redirect, admin_url() ) ) {
			return;
		}
		$error = __( 'You need to login to access this website.' );
	}
);
// Force logged-in only traffic for the API.
add_filter(
	'rest_authentication_errors',
	static function ( $result ) {
		if ( is_wp_error( $result ) ) {
			return $result;
		}
		if ( ! is_user_logged_in() ) {
			return new WP_Error(
				'rest_not_logged_in',
				__( 'This content is restricted to logged-in users.' ),
				array( 'status' => 401 )
			);
		}
		return $result;
	}
);
// Don't allow indexing.
add_action( 'pre_option_blog_public', '__return_zero' );

Comments

Add a Comment