Last active
February 8, 2018 13:29
-
-
Save kjbenk/3a17a04eb4a7e70f419bcb0a6efa5057 to your computer and use it in GitHub Desktop.
WordPress: Custom User Roles
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Customize user roles. | |
*/ | |
/** | |
* Class User_Roles. | |
*/ | |
class User_Roles { | |
/** | |
* The cache key. | |
* | |
* @var string | |
*/ | |
private $cache_key = 'user_roles_hash'; | |
/** | |
* An array of the user roles to add. | |
* | |
* @var array | |
*/ | |
private $user_roles = []; | |
/** | |
* Existing instance. | |
* | |
* @var array | |
*/ | |
protected static $instance; | |
/** | |
* Get class instance. | |
* | |
* @return object | |
*/ | |
public static function instance() { | |
if ( ! isset( static::$instance ) ) { | |
static::$instance = new static(); | |
static::$instance->setup(); | |
} | |
return static::$instance; | |
} | |
/** | |
* Setup the class. | |
*/ | |
private function setup() { | |
// Add custom user roles here. | |
// Setup the user roles. | |
$this->setup_user_roles(); | |
} | |
/** | |
* Check if we need to add the user roles. | |
*/ | |
private function setup_user_roles() { | |
// Check if we have already added our roles. | |
$current_hash = get_transient( $this->cache_key ); | |
// We have not setup the user roles yet or they changed. | |
if ( | |
false === $current_hash | |
|| $current_hash !== $this->get_roles_hash() | |
) { | |
$this->add_user_roles(); | |
// Save the current hash. | |
set_transient( $this->cache_key, $this->get_roles_hash() ); | |
} | |
} | |
/** | |
* Add the user roles. | |
*/ | |
private function add_user_roles() { | |
foreach ( $this->user_roles as $role => $args ) { | |
if ( get_role( $role ) ) { | |
remove_role( $role ); | |
} | |
add_role( $role, $args['display_name'], $args['caps'] ); | |
} | |
} | |
/** | |
* Get the roles hash. | |
* | |
* @return string The hash code from the current state of the user roles. | |
*/ | |
private function get_roles_hash() { | |
return md5( wp_json_encode( $this->user_roles ) ); | |
} | |
} | |
User_Roles::instance(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment