This website uses cookies to allow us to see how the site is used. If you continue to use this site, we assume that you are okay with this. If you want to use the sites without cookies, please see our privacy policy.

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 code and be nice ^_^

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.