How to use is_admin() to safety check that WordPress users are administrator.

Last Updated on

The is_admin() is one of the most used functions that check whether you are in the administrator interface. If you are a new WordPress developer, you may probably get misunderstood of the function name is_admin(). The is_admin() doesn’t check whether the role and capabilities of the visitors or users are administrator, but it check that you are in administrator interface or not.

Unsafe is_admin() use case

To check if WordPress users are an administrator with is_admin() is probably unsafe because it doesn’t check if the user is already login and what’s their capabilities and roles. If you are using it to check if the user is authorized to access it or not, it can lead to a serious problem of security. It happened in real-world scenario. According to the WordFence and WebArx plugin security check, this can risk leaking out your WordPress database, open the door of Cross Site Scripting (XSS) flaws and even more.

if ( ! is_admin() ) {
    wp_die( 'You do not have authorization to view this page!' ); // DANGEROUS!!!
}

Better is_admin() use case

For better security, we add the is_user_logged_in() and user_can() to harden the security to avoid most common vulnerability of theme and plugins.


if ( ! is_admin() && ! is_user_logged_in() && ! user_can( $id_user, 'administrator' ) ) {
    wp_die( 'You do not have authorization to view this page!' );
}

Even better for security

You can also harden the conditional flow of security by adding current_user_can() to check whether the current user has the specific capabilities. At here, I’ll want to check whether its user have the capability of editing the post.

if( !current_user_can( 'edit_posts' ) ){
     wp_die( 'You do not have authorization to edit this post!' );
}
Spread Your Love By Sharing It On:
Write With ❤️ By Jorcus

Leave a Comment