Check Logged in User Role

Advertisement

Check logged in user role. Use function  wp_get_current_user() to get the current/logged in user info.

Usage:

var_dump( prefix_user_has_role( 'administrator' ) );

// Output:
// bool(true)

Snippet:


<?php
if( ! function_exists( 'prefix_user_has_role' ) ) :
/**
* Check logged in user has role
*
* @todo Change `prefix` with your own unique slug.
*
* E.g. var_dump( prefix_user_has_role( 'administrator' ) );
*
* Output:
*
* bool(true)
*
* @since 1.0.0
* @param string $role User role.
* @return boolean User role status.
*/
function prefix_user_has_role( $role = '' )
{
// Not logged in? Return false.
if( ! is_user_logged_in() ) {
return false;
}
// Role exist? Return true.
if ( in_array( $role, (array) wp_get_current_user()->roles ) ) {
return true;
}
// Default. Return false.
return false;
}
endif;

Leave a Reply