Categories
Uncategorized

WordPress: How to run PHP scripts only when logged in as admin

Here’s a new tiny function that will help you run PHP code in WordPress only when you (or other admin-level users) are logged in.

When developing for WordPress , sometimes you may be looking to run a small piece of code that you and only you can see, without disturbing the peaceful, beautiful flow of your carefully crafted website (and without annoying your users, of course).

So, here’s a small function I created, admin_level(), that’s come in handy several times while I’ve worked with WordPress. By placing this function in your theme’s functions.php file, you will be able to create “test areas” throughout your site where you can run code only when someone with enough permissions (e.g. an “admin” user) is logged in.

NOTE: Testing should ALWAYS be done on a test server separate from production!!! But hey, quick and dirty also does it =)

The admin_level() function

 

<?php
function admin_level($user_login=''){
	global $current_user;
	get_currentuserinfo();

	if(current_user_can('level_10')) {
		if ($user_login!=''){
			if($current_user->user_login==$user_login){
				return true;
			} else {
				return false;
			}
		} else {
			return true;
		}
	} else {
		return false;
	}
}
?>

The admin_level() function has only one optional parameter $user_login, which you can use to basically say “Hey, check that I’m user ‘username’ and have admin access.” If those conditions are met, it returns true, otherwise it returns false.

Examples

Create a “test area” in functions.php

After adding the admin_level()  function to your functions.php file, you can start using it to test things right away. Here’s an example of a “test area” within the function.php file itself (I usually do this at the end of the file, so I know where it is):

<?php

//Test Area

   //Only run following code if logged in as admin

   if( admin_level($user_login = 'vidal') ){

      //run your awesome code right here, admin!!!

   }

//End Test Area

?>

 

Another (inverse) example: redirecting from header.php

Here’s a redirecting script I used on header.php to send anyone who was NOT logged in as admin user ‘vidal’ somewhere else:

<?php

if( !admin_level($user_login = 'vidal') ){

   header('Location:http://www.getouttahere.com);

   exit();
}

?>

This one came in handy, since I needed to temporarily redirect people to another site and keep on working quickly to fix the site ASAP.

 

So, there you have it. This is a very simple way to keep scripts safely confined (even if they fail while you are testing them). I hope you find it useful!

 

 

 

Leave a Reply

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