If you are building a plugin or a custom WordPress site, for certain pages, you might want to check if the user is logged in. This way you can restrict pages to registered users.

The code is really simple:

if ( is_user_logged_in() ) {
	// The user is logged in...
} else {
	// The user hasn't logged in...
}

The function is_user_logged_in returns true if the user is logged in and false if not.

If you want, you can redirect the user to appropriate pages based on whether or not they are logged in:

if ( is_user_logged_in() ) {
	$logged_in = true;
} else {
	// This user hasn't logged in, redirect them to the Login page.
	header("location: https://my-website.com/login");
}

The above code will redirect the user to the login page on your website if they aren’t logged in.

Make sure to place this code at the top of your code. If you are going to use the header function to redirect the user, make sure this code is run before any HTML is sent to the browser.

Pin It on Pinterest

Share This