A WordPress function to stop non logged in users accessing a page or pages

If you’ve ever tried to build a mini application with WordPress you’ll probably know that you need to use multiple page templates that only registered users can access, so the easiest thing to do is create a WordPress function to stop non logged in users accessing a page or pages, if they can’t then they should get kicked away, gently of course!

Here is one really simple way I’ve used many times to do this.

First of all create this function in your functions.php file

// check users or die
function check_logged_in_users() {
	global $current_user;
	if ( !is_user_logged_in()) {
		wp_die("<p>To access this page you need to login first! Why don't you go back and try again.</p>", "Oh dear, something went wrong!", array( 'response' => 500, 'back_link' => true ));

So next you need to add the function at the top of each page you’d like to hide from non logged in users, somewhere before the get_header() function should do it, looks something like this:

	Template Name: This page is for logged in users only

Now all page templates with this function will only allow logged in users to access the page.


A geek who likes to cook with wp ingredients!

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>