WP_Roles{} WP 2.0.0

Клас дозволяє керувати ролями та можливостями ролей у WordPress.

Опції ролі прості, структура організована за назвою ролі, яка є ключем основного масиву. Можливості ролі перебувають у вкладеному масиві із двох параметрів: name і capabilities:

array (
	'rolename' => array (
		'name' => 'rolename',
		'capabilities' => array()
	)
)

Працює у зв’язці з WP_Role, яка створює об’єкти для властивості $this->role_objects .

Ролі та можливості не генеруються постійно, а записуються в опцію:wp_user_roles

Щоб отримати глобальний екземпляр цього класу, завжди використовуйте допоміжну функцію wp_roles() .

Основа для:
remove_role() ,
add_role() ,
get_role()

Хуки із класу

Використання

global $wp_roles;
$wp_roles = новий WP_Roles();

// або просто
$wp_roles = wp_roles();

Властивості класу

$roles
(масив)

Список ролей та можливостей. Аналогічний властивості $role_objects містить слід. структуру:

array (
   'rolename' => array (
   'name' => 'rolename',
   'capabilities' => array()
   )
)
$role_objects
(масив)

Список об’єктів ролей. Містить таку структуру:

array (
   'rolename' => array (
	   'name' => 'rolename',
	   'capabilities' => array()
   )
)
$role_names
(масив)

Список лише назв ролей:

[role_names] => Array (
	[administrator] => Адміністратор
	[editor] => Редактор
	[author] => Автор
	[contributor] => Учасник
	[subscriber] => Передплатник
)
$role_key
(рядок)
Назва опції, в якій буде список ролей, пр: ‘wp_user_roles’.
$use_db
(логічний)
Чи використовувати базу даних для отримання та розміщення ролей.

Методи

__construct()
(public)
Конструктор. Викликає
_init() .


Повертає: нічого
__call(
$name ,
$arguments )
(public)
Для зворотної сумісності працювали неіснуючі методи.


Повертає: false/різне
_init()
(protected)

Встановлює властивості об’єкта. Використовує глобальні: $wpdb , $wp_user_roles .

Якщо глобальна $wp_user_roles не встановлена, то як ключ буде використана конструкція “{$wpdb->prefix}user_roles” .
Повертає: нічого

reinit()
(public)
Пере-ініціалізує об’єкт. Зазвичай викликається функцією
switch_to_blog() після того, як перемикає wpdb на інший блог у системі MU.


Повертає: нічого
add_role(
$role ,
$display_name ,
$capabilities =
array() )
(public)
Додає роль із можливостями до списку. Оновлює список ролей, якщо роль ще не існує.

Можливості визначаються у такому форматі:
array( ‘read’ => true );

Щоб заборонити зазначену можливість, значення потрібно встановити false:
array( ‘read’ => false );

Для цього методу є функція обгортка:
add_role() .


Повертає: WP_Role|нічого. WP_Role, якщо роль було додано.
remove_role(
$role )
(public)
Видаляє роль за назвою. Для цього методу є функція обгортка:
remove_role() .


Повертає: нічого
add_cap(
$role ,
$cap ,
$grant = true )
(public)
Додає можливість
$cap до вказаної у
$role ролі. Логічне
$grant визначає дозволити чи заборонити зазначену можливість. Детальний опис:
add_cap()


Повертає: нічого
remove_cap(
$role ,
$cap )
(public)
Видаляє можливість
$cap у вказаної в
$role ролі.


Повертає: нічого
get_role(
$role )
(public)
Отримує об’єкт вказаної ролі.


Повертає: Об’єкт WP_Role, якщо роль знайдена або null, якщо немає ролі.
get_names()
(public)
Отримує список найменувань усіх ролей у вигляді масиву.


Повертає: масив назв
is_role(
$role )
(public)
Перевіряє чи вказана роль у списку поточних ролей.


Повертає: true|false

Приклади

0

#1 Що містить масив ролей

print_r(wp_roles());
/*
WP_Roles Object
(
	[roles] => Array
		(
			[administrator] => Array
				(
					[name] => Administrator
					[capabilities] => Array
						(
							[switch_themes] => 1
							[edit_themes] => 1
							[activate_plugins] => 1
							[edit_plugins] => 1
							[edit_users] => 1
							[edit_files] => 1
							[manage_options] => 1
							[moderate_comments] => 1
							[manage_categories] => 1
							[manage_links] => 1
							[upload_files] => 1
							[import] => 1
							[unfiltered_html] => 1
							[edit_posts] => 1
							[edit_others_posts] => 1
							[edit_published_posts] => 1
							[publish_posts] => 1
							[edit_pages] => 1
							[read] => 1
							[level_10] => 1
							[level_9] => 1
							[level_8] => 1
							[level_7] => 1
							[level_6] => 1
							[level_5] => 1
							[level_4] => 1
							[level_3] => 1
							[level_2] => 1
							[level_1] => 1
							[level_0] => 1
							[edit_others_pages] => 1
							[edit_published_pages] => 1
							[publish_pages] => 1
							[delete_pages] => 1
							[delete_others_pages] => 1
							[delete_published_pages] => 1
							[delete_posts] => 1
							[delete_others_posts] => 1
							[delete_published_posts] => 1
							[delete_private_posts] => 1
							[edit_private_posts] => 1
							[read_private_posts] => 1
							[delete_private_pages] => 1
							[edit_private_pages] => 1
							[read_private_pages] => 1
							[delete_users] => 1
							[create_users] => 1
							[unfiltered_upload] => 1
							[edit_dashboard] => 1
							[update_plugins] => 1
							[delete_plugins] => 1
							[install_plugins] => 1
							[update_themes] => 1
							[install_themes] => 1
							[manage_downloads] => 1
							[manage_database] => 1
							[democracy_admin] => 1
							[update_core] => 1
							[list_users] => 1
							[remove_users] => 1
							[add_users] => 1
							[promote_users] => 1
							[edit_theme_options] => 1
							[delete_themes] => 1
							[export] => 1
						)

				)

			[editor] => Array
				(
					[name] => Editor
					[capabilities] => Array
						(
							[moderate_comments] => 1
							[manage_categories] => 1
							[manage_links] => 1
							[upload_files] => 1
							[unfiltered_html] => 1
							[edit_posts] => 1
							[edit_others_posts] => 1
							[edit_published_posts] => 1
							[publish_posts] => 1
							[edit_pages] => 1
							[read] => 1
							[level_7] => 1
							[level_6] => 1
							[level_5] => 1
							[level_4] => 1
							[level_3] => 1
							[level_2] => 1
							[level_1] => 1
							[level_0] => 1
							[edit_others_pages] => 1
							[edit_published_pages] => 1
							[publish_pages] => 1
							[delete_pages] => 1
							[delete_others_pages] => 1
							[delete_published_pages] => 1
							[delete_posts] => 1
							[delete_others_posts] => 1
							[delete_published_posts] => 1
							[delete_private_posts] => 1
							[edit_private_posts] => 1
							[read_private_posts] => 1
							[delete_private_pages] => 1
							[edit_private_pages] => 1
							[read_private_pages] => 1
							[democracy_admin] => 1
						)

				)

			[author] => Array
				(
					[name] => Author
					[capabilities] => Array
						(
							[upload_files] => 1
							[edit_posts] => 1
							[edit_published_posts] => 1
							[publish_posts] => 1
							[read] => 1
							[level_2] => 1
							[level_1] => 1
							[level_0] => 1
							[delete_posts] => 1
							[delete_published_posts] => 1
						)

				)

			[contributor] => Array
				(
					[name] => Contributor
					[capabilities] => Array
						(
							[edit_posts] => 1
							[read] => 1
							[level_1] => 1
							[level_0] => 1
							[delete_posts] => 1
						)

				)

			[subscriber] => Array
				(
					[name] => Subscriber
					[capabilities] => Array
						(
							[read] => 1
							[level_0] => 1
						)

				)

		)

	[role_objects] => Array
		(
			[administrator] => WP_Role Object
				(
					[name] => administrator
					[capabilities] => Array
						(
							[switch_themes] => 1
							[edit_themes] => 1
							[activate_plugins] => 1
							[edit_plugins] => 1
							[edit_users] => 1
							[edit_files] => 1
							[manage_options] => 1
							[moderate_comments] => 1
							[manage_categories] => 1
							[manage_links] => 1
							[upload_files] => 1
							[import] => 1
							[unfiltered_html] => 1
							[edit_posts] => 1
							[edit_others_posts] => 1
							[edit_published_posts] => 1
							[publish_posts] => 1
							[edit_pages] => 1
							[read] => 1
							[level_10] => 1
							[level_9] => 1
							[level_8] => 1
							[level_7] => 1
							[level_6] => 1
							[level_5] => 1
							[level_4] => 1
							[level_3] => 1
							[level_2] => 1
							[level_1] => 1
							[level_0] => 1
							[edit_others_pages] => 1
							[edit_published_pages] => 1
							[publish_pages] => 1
							[delete_pages] => 1
							[delete_others_pages] => 1
							[delete_published_pages] => 1
							[delete_posts] => 1
							[delete_others_posts] => 1
							[delete_published_posts] => 1
							[delete_private_posts] => 1
							[edit_private_posts] => 1
							[read_private_posts] => 1
							[delete_private_pages] => 1
							[edit_private_pages] => 1
							[read_private_pages] => 1
							[delete_users] => 1
							[create_users] => 1
							[unfiltered_upload] => 1
							[edit_dashboard] => 1
							[update_plugins] => 1
							[delete_plugins] => 1
							[install_plugins] => 1
							[update_themes] => 1
							[install_themes] => 1
							[manage_downloads] => 1
							[manage_database] => 1
							[democracy_admin] => 1
							[update_core] => 1
							[list_users] => 1
							[remove_users] => 1
							[add_users] => 1
							[promote_users] => 1
							[edit_theme_options] => 1
							[delete_themes] => 1
							[export] => 1
						)

				)

			[editor] => WP_Role Object
				(
					[name] => editor
					[capabilities] => Array
						(
							[moderate_comments] => 1
							[manage_categories] => 1
							[manage_links] => 1
							[upload_files] => 1
							[unfiltered_html] => 1
							[edit_posts] => 1
							[edit_others_posts] => 1
							[edit_published_posts] => 1
							[publish_posts] => 1
							[edit_pages] => 1
							[read] => 1
							[level_7] => 1
							[level_6] => 1
							[level_5] => 1
							[level_4] => 1
							[level_3] => 1
							[level_2] => 1
							[level_1] => 1
							[level_0] => 1
							[edit_others_pages] => 1
							[edit_published_pages] => 1
							[publish_pages] => 1
							[delete_pages] => 1
							[delete_others_pages] => 1
							[delete_published_pages] => 1
							[delete_posts] => 1
							[delete_others_posts] => 1
							[delete_published_posts] => 1
							[delete_private_posts] => 1
							[edit_private_posts] => 1
							[read_private_posts] => 1
							[delete_private_pages] => 1
							[edit_private_pages] => 1
							[read_private_pages] => 1
							[democracy_admin] => 1
						)

				)

			[author] => WP_Role Object
				(
					[name] => author
					[capabilities] => Array
						(
							[upload_files] => 1
							[edit_posts] => 1
							[edit_published_posts] => 1
							[publish_posts] => 1
							[read] => 1
							[level_2] => 1
							[level_1] => 1
							[level_0] => 1
							[delete_posts] => 1
							[delete_published_posts] => 1
						)

				)

			[contributor] => WP_Role Object
				(
					[name] => contributor
					[capabilities] => Array
						(
							[edit_posts] => 1
							[read] => 1
							[level_1] => 1
							[level_0] => 1
							[delete_posts] => 1
						)

				)

			[subscriber] => WP_Role Object
				(
					[name] => subscriber
					[capabilities] => Array
						(
							[read] => 1
							[level_0] => 1
						)

				)

		)

	[role_names] => Array
		(
			[administrator] => Administrator
			[editor] => Editor
			[author] => Author
			[contributor] => Contributor
			[subscriber] => Subscriber
		)

	[role_key] => wp_user_roles
	[use_db] => 1
)
*/
0

#2 Створимо нову роль: “Основний учасник”:

$result = add_role(
	'basic_contributor', 'Основний учасник',
	array(
		'read' => true, // true дозволяє цю можливість
		'edit_posts' => true, // true дозволяє редагувати пости
		'delete_posts' => false, // false забороняє видаляти пости
	)
);
if ( null !== $result ) {
	echo 'Ура! Нова роль створена!';
}
else {
	echo 'Ой... Така роль вже існує.';
}
0

#3 Видалимо роль “передплатник” (subscriber):

register_deactivation_hook( __FILE__, function(){
	remove_role( 'subscriber');
} );

список змін

З версії 2.0.0Введено.

WP Roles{} WP 6.0.2

class WP_Roles { /** * List of roles and capabilities. * * @ Since 2.0.0 * @var array[] */ public $roles; /** * List of the role objects. * * @ Since 2.0.0 * @var WP_Role[] */ $role_objects = array(); /** * List of role names. * * @ Since 2.0.0 * @var string[] */ $role_names = array(); /** * Option name for storing role list. * * @ Since 2.0.0 * @var string */ public $ role_key; /** * Для використання вашої програми для відшкодування і зберігання. * * @ Since 2.1.0 * @var bool */ public $use_db = true; /** * Веб-сайт ID roles є ініціалізованим для. * * @ Since 4.9.0 * @var int */ protected $site_id = 0; /** * Constructor * * @ Since 2.0.0 * @since 4.9.0 The `$site_id` argument was added. * * @global array $wp_user_roles Використовується для налаштування 'roles' property value. * * @param int $site_id Ідентифікатор ID для ін'єт. Default is the current site. */ public function __construct( $site_id = null ) { global $wp_user_roles; $this->use_db = empty( $wp_user_roles ); $this->for_site( $site_id ); } /** * Make private/protected methods readable for backward compatibility. * * @ Since 4.0.0 * * @param string $name Method to call. * @param array $arguments Arguments to pass when calling. * @return mixed|false Return value of callback, false otherwise. */ public function __call( $name, $arguments ) { if ( '_init' === $name ) { return $this->_init( ...$arguments ); } return false; } /** * Set up the object properties. * * The role key is set to the current prefix for the $wpdb object with * 'user_roles' appended. Якщо $wp_user_roles global is set, then it will * be used and the role option will not be updated or used. * * @ Since 2.1.0 * @deprecated 4.9.0 Use WP_Roles::for_site() */ protected function _init() { _deprecated_function( __METHOD__, '4.9.0', 'WP_Roles::for_site()' ); $this->for_site(); } /** * Reinitialize the object * * Recreates the role objects. Цей типово називається тільки switch_to_blog() * Після перемикання wpdb до нового сайту ID. * * @ Since 3.5.0 * @deprecated 4.7.0 Use WP_Roles::for_site() */ public function reinit() { _deprecated_function( __METHOD__, '4.7.0', 'WP_Roles::for_site()' ); $this->for_site(); } /** * Add role name with capabilities to list. * * Updates the list of roles, якщо the role doesn't already exist. * * Capabilities are defined in the following format `array( 'read' => true );` * Для explicitly deny a role a capability ви можете встановити значення для того, щоб capability to false. * * @ Since 2.0.0 * * @param string $ role Role name. * @param string $display_name Role display name. * @param bool[] $capabilities List of capabilities keyed by the capability name, * eg array( 'edit_posts' => true, 'delete_posts' => false ). * @return WP_Role|void WP_Role об'єкт, якщо role is added. */ public function add_role( $role, $display_name, $capabilities = array() ) { if ( empty( $role ) || isset( $this->roles[ $role ] ) ) { return; } $this->roles[ $role ] = array( 'name' => $display_name, 'capabilities' => $capabilities, ); if ( $this->use_db ) { update_option( $this->role_key, $this->roles ); } $this->role_objects[ $role ] = new WP_Role( $role, $capabilities ); $this->role_names[ $role ] = $display_name; return $this->role_objects[ $role ]; } /** * Remove role by name. * * @ Since 2.0.0 * * @param string $ role Role name. */ public function remove_role( $role ) { if ( ! isset( $this->role_objects[ $role ] ) ) { return; } unset( $this->role_objects[ $role ] ); unset( $this->role_names[ $role ] ); unset( $this->roles[ $role ] ); if ( $this->use_db ) { update_option( $this->role_key, $this->roles ); } if ( get_option( 'default_role' ) == $role ) { update_option( 'default_role', 'subscriber'); } } /** * Add capability to role. * * @ Since 2.0.0 * * @param string $ role Role name. * @param string $cap Capability name. * @param bool $grant Optional. Whether role is capable of performing capability. * Default true. */ public function add_cap( $role, $cap, $grant = true ) { if ( ! isset( $this->roles[ $role ] ) ) { return; } $this->roles[ $role ]['capabilities'][ $cap ] = $grant; if ( $this->use_db ) { update_option( $this->role_key, $this->roles ); } } /** * Remove capability from role. * * @ Since 2.0.0 * * @param string $ role Role name. * @param string $cap Capability name. */ public function remove_cap( $role, $cap ) { if ( ! isset( $this->roles[ $role ] ) ) { return; } unset( $this->roles[ $role ]['capabilities'][ $cap ] ); if ( $this->use_db ) { update_option( $this->role_key, $this->roles ); } } /** * Retrieve role object by name. * * @ Since 2.0.0 * * @param string $ role Role name. * @return WP_Role|null WP_Role object if found, null if the role does not exist. */ public function get_role( $role ) { if ( isset ( $this-> role_objects [ $ role ] ) ) { return $this->role_objects[ $role ]; } else { return null; } } /** * Retrieve list of role names. * * @ Since 2.0.0 * * @return string[] List of role names. */ public function get_names() { return $this->role_names; } /** * Whether role name є поточно в аркуші доступних roles. * * @ Since 2.0.0 * * @param string $role Відомості про те, щоб переглянути. * @return bool */ public function is_role( $role ) { return isset($this->role_names[$role]); } /** * Initializes all of the available roles. * * @ Since 4.9.0 */ public function init_roles() { if ( empty( $this->roles ) ) { return; } $this->role_objects = array(); $this->role_names = array(); foreach ( array_keys( $this->roles ) as $role ) { $this->role_objects[ $role ] = new WP_Role( $role, $this->roles[ $role ]['capabilities'] ); $this->role_names[ $role ] = $this->roles[ $role ]['name']; } /** * Після roles має бути initialized, allow plugins до їх своїх roles. * * @ Since 4.7.0 * * @param WP_Roles $wp_roles Оцінка до об'єкта WP_Roles. */ do_action( 'wp_roles_init', $this ); } /** * Sets the site to operate on. Defaults to the current site. * * @ Since 4.9.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @param int $site_id Ідентифікатор ID для ін'єт. Default is the current site. */ public function for_site( $site_id = null ) { Global $wpdb; if ( ! empty( $site_id ) ) { $this->site_id = absint( $site_id ); } else { $this->site_id = get_current_blog_id(); } $this->role_key = $wpdb->get_blog_prefix( $this->site_id ) . 'user_roles'; if ( ! empty( $this->roles ) && ! $this->use_db ) { return; } $this->roles = $this->get_roles_data(); $this->init_roles(); } /** * Gets the ID of the site for which roles are currently initialized. * * @ Since 4.9.0 * * @return int Site ID. */ public function get_site_id() { return $this->site_id; } /** * Gets the available roles data. * * @ Since 4.9.0 * * @global array $wp_user_roles Використовується для налаштування 'roles' property value. * * @return array Roles array. */ protected function get_roles_data() { global $wp_user_roles; if ( ! empty( $wp_user_roles ) ) { return $wp_user_roles; } if ( is_multisite() && get_current_blog_id() != $this->site_id ) { remove_action( 'switch_blog', 'wp_switch_roles_and_user', 1); $roles = get_blog_option( $this->site_id, $this->role_key, array() ); add_action( 'switch_blog', 'wp_switch_roles_and_user', 1, 2); return $roles; } return get_option( $this->role_key, array() ); } }

Залишити відповідь

Ваша e-mail адреса не оприлюднюватиметься. Обов’язкові поля позначені *