Check If Current User Is Administrator in Wordpress

How to check if currently in Wordpress Admin?

Duh, this was too obvious. For some reason I was thinking this had to do with an admin user.
if(is_admin()) { ...output my admin stuff....}

http://codex.wordpress.org/Function_Reference/is_admin

Check if user is an admin by username or email only

As I noted in a comment user_pass_ok( $user, $pass ) is deprecated in favor of wp_authenticate.

Additionally, WordPress has an amazing Capabilities API that goes far beyond Roles. I would strongly recommend reading up on it.

For a brief example, if I wanted to grant a user access to manage WordPress options (a capability called manage_options that is inherited from the Administrator role), all I have to do is say current_user_can('manage_options') or use the WP_User->has_cap(...) function.

Matching based on capabilities is usually much more flexible that matching on a Role... for example imagine my site had a second role called "Developers". If you gated access based on roles, and you wanted to give users in the developer role access to your feature, you would need to add a second check whenever you need to verify a users permissions: ($role == 'administrator' || $role == 'developer')

So, if you have a user logged in already then you can always verify their capabilities with:

current_user_can( 'manage_options' ) // all admins have 'manage_options'

or define your own custom cap, give it to all administrators:

function add_custom_admin_caps() {
$role = get_role( 'administrator' );

$role->add_cap( 'access_my_admin_zone' );
}
add_action( 'admin_init', 'add_custom_admin_caps');

and check the custom cap against the current user

current_user_can( 'access_my_admin_zone' )

The added benefit to capabilities is that WordPress will automatically check the current user's permissions when rendering the WP Admin menu if you register your admin section with one of the add_*_page functions (add_menu_page()) and a capability like 'manage_options'

add_menu_page ( $title, $menu_title, $capability, $menu_slug, $function, $icon_url, $position)

Lastly, It was a bit unclear as to whether you were logging in users yourself, if so I would propose this alternative if you are logging in the user from scratch (i.e. not using WordPress's login form):

$user = wp_authenticate( $user, $pass );

if ( is_a( $user, 'WP_User' ) && $user->has_cap( 'manage_options' ) ) {
// success
} else {
// fail
}

You will also need to call current_user_can( 'manage_options' ) during every page load of your custom admin to verify that the user is logged in and has permissions, if that fails, then direct them to your custom login page... or possibly, the wordpress login page with auth_redirect().

In wordpress plugin check if user is admin before running a function

So I was doing this wrong, the answer supplied by ReLeaf is partially correct but nobody pointed out that instead of trying to wrap the function like the example I gave in the original question and is why i was getting a blank admin screen :

global $current_user;
if ( $current_user->role[0]=='administrator' ) {

function remove_post_metaboxes() {
remove_meta_box( 'formatdiv','album','normal' );
}
add_action('admin_menu','remove_post_metaboxes');
}

I should have had the conditional inside the function instead :

function remove_post_metaboxes() {
global $current_user;
if ( $current_user->role[0]=='administrator' ) {
remove_meta_box( 'formatdiv','album','normal' );
}
}
add_action('admin_menu','remove_post_metaboxes');

So that's how it's done, thanks me for pointing it out to me ;)

Using WordPress authentication while checking if user is an administrator

First: This question is related to Check if user is an admin by username or email only

Second: the logic in your first block is very strange... this is what is should resemble

Use WordPress Login Workflow

You should always use the built in WordPress login form and authentication workflow. It is not that hard to use and rolling your own login page makes your application very insecure unless you do it exactly right

To use the default WordPress login flow, put something like this in your Dashboard's common PHP file

<?php 
require_once 'path/to/wp-load.php';
// Before every page load
if ( ! is_user_logged_in() ) {
// Not logged in at all... redirect to WP Login Page
auth_redirect();
exit(); // Exit to be safe
} elseif ( ! in_array( 'administrator', wp_get_current_user()->roles ) ) {
wp_logout(); // Destroy their login session
wp_die('You must be an administrator'); // Die with a nice error page
}

Let me explain this workflow:

First we import wp-load.php. This is somewhat frowned upon as well and there might be a lighter way of doing this, but for now it should work well

Now, say a user loads https://example.com/my-admin/index.php, your common.php will first check if the user is logged in. If not then it will call auth_redirect() and exit which will redirect the user to https://example.com/wp-login.php?return_url=https%3A%2F%2Fexample.com%2Fmy-admin%2Findex.php

The user will login using the wp-login page and then they will be redirected back to https://example.com/my-admin/index.php, where your common.php will now recognize is_logged_in() as true... so we step to the next elseif where it will check if the user is an administrator. If not then it will kill their authentication session and fail with a wp_die We kill the auth session so that if they reload the page they will be brought back to the login page to enter credentials for an admin and not repeatedly shown the wp_die page, you can tweak this however you wish as this might not be the desired behavior (perhaps redirect to /wp-admin/... or provide a link in the wp_die for the regular /wp-admin/)

if they do have the Administrator role, then execution of the request will continue and the dashboard will be accessible.

Please note that for this to work you will need to have your dashboard running on the same domain as your WordPress install... or else the cookies won't transfer over.

Roll your own login page. This is bad practice

It is hard to do... this example doesn't include Nonces, honeypots, or any other security features that you will get with the standard login form (either with default core or from additional plugins)

<?php 
// Your login.php page

// Really, no really, this should just be done with WordPress's default login page with an auth_redirect()
// Really this is not recommended, it's really bad practice, and much less secure
// You've been warned

// If they provided a username and password, then check them
if ( isset( $_POST['username'] ) && isset( $_POST['password'] ) ) {
$username = $_POST['username']
$username = $_POST['password']
// Check the username and password with WordPress to see if they are for any user
$user = wp_authenticate( $username, $password );
$error = '';
if ( is_a( $user, 'WP_User' ) ) {
// Verify that the user is an admin
if ( in_array( 'administrator', (array) $user->roles ) ) {
// Redirect them to the dashboard
wp_redirect('dashboard.php');
exit();
} else {
$error = "Correct password, but not an Admin : (";
}
} else {
$error = "Wrong password :(";
}
}
// The Login Page
?>
<html>
<head>
<title> My Login </title>
</head>
<body>
<form action="login.php" method="POST">
<?php if ( $error ): ?>
<div class="error"><?php echo $error; ?></div>
<?php endif; ?>
<label>
Username:
<input type="text" name="username" placeholder="username" required />
</label>
<label>
Password:
<input type="password" name="password" placeholder="password" required />
</label>
</form>
</body>
</html>

Before you load any other page besides your login page you should have this code

<?php
if ( ! is_user_logged_in() || ! in_array( 'administrator', wp_get_current_user()->roles ) ) {
wp_redirect('login.php?error=Please%20Login');
exit();
}
// now you can do your stuff

PHP - What's opposite to current_user_can?

Just negate the condition with !:

function my_custom_init() {
if (!current_user_can('administrator')) {
remove_post_type_support( 'company', 'editor' );
remove_post_type_support( 'company', 'excerpt' );
}
}
add_action( 'init', 'my_custom_init' );


Related Topics



Leave a reply



Submit