Tutorial: How to validate whether a user has logged into WordPress

Since i can't find this information anywhere on Google and WordPress search box, i will write a post out to save time for people who want to validate whether a person has logged into WordPress to access their external plugin page (another page that is not resist in WordPress Administrator panel).

Problem

My plugin has a file mangement page that help manage the site images from my plugin but the page was external and could be access by ANYONE as long as they have the URL, this is not secure at all. Thus, i wanted to know whether WordPress has any method or action hook that allow to validate a user upon entering that page. I tried Google and WordPress search box for any open question for this. Unfortunately, there isn't any.

Solution

In order to use methods exist in WordPress in an external page, we will have to include them into your page. The file i used to include in my page was 'wp-config.php' in WordPress. This will include all WordPress methods and dependency that these methods have so we won't have to worry that our plugin will just break suddenly.

The other important thing after the main page has been imported is the method. WordPress provides a method called 'is_user_logged_in()', with this method, we can validate whether that particular user has logged into WordPress to check whether they are the correct user. The following code illustrate the above explanation,

require_once '../../../../wp-config.php';
if ( is_user_logged_in() ) 
{
	echo "i am logged in";
}

This is jusst a demo so the real code of mine won't be here to confuse you. The require_once path used is just to navigate downwards. So any user of WordPress can access the page? Of course not! Using the following code we can validate which level of access the user has,

require_once '../../../../wp-config.php';
global $current_user;
get_currentuserinfo();
$level = $current_user->user_level;
if ( is_user_logged_in() && $level == "10") 
	echo "you have access";
else
	echo "you do not have access";

This way we will have to validate what access level this particular user has with the global variable $userdata, WordPress doc has demonstrate this pretty nicely and by checking its access level, you can restrict what level of user is allowed to access your page.

One thought on “Tutorial: How to validate whether a user has logged into WordPress

Comments are closed.