WP_Roles<> │ WP 2.0.0 │ AllowDynamicProperties
Класс позволяет управлять ролями и возможностями ролей в WordPress. Опции роли просты, структура организована по названию роли, которое является ключом основного массива. Возможности роли находятся во вложенном массиве из двух параметров: name и capabilities:
array ( 'rolename' => array ( 'name' => 'rolename', 'capabilities' => array() ) )
Чтобы получить глобальный экземпляр этого класса, всегда используйте вспомогательную функцию wp_roles().
Хуки из класса
Использование
global $wp_roles; $wp_roles = new WP_Roles(); // или просто $wp_roles = wp_roles();
Свойства класса
$roles(массив) Список ролей и возможностей. Аналогичен свойству $role_objects и содержит след. структуру:
array ( 'rolename' => array ( 'name' => 'rolename', 'capabilities' => array() ) )
array ( 'rolename' => array ( 'name' => 'rolename', 'capabilities' => array() ) )
[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 не установлена, то в качестве ключа будет использована конструкция «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
Примеры
#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 ) */
How to get current user role in WordPress
This article shows how to get the user role of the current user in WordPress from within the loop using PHP code.
WordPress is a very dynamic and flexible platform. You can use it for pretty much anything. When writing any custom code for your WordPress website, it’s important to accurately identify and authenticate the user login that is executing the code.
WordPress offers a user accounts functionality with user role interface for users to create and manage their profiles. If a user has a role of Administrator, Editor or Author role, that means you can let him or her to update their profile information from the WordPress dashboard. Moreover, WordPress itself defines default roles using the global variable $wp_roles . You can edit these roles by adding or removing capabilities for each role or create new custom user role.
WordPress offers many functions for checking the current user role of a user. Using these functions, you can easily decide what content, functionality, or actions should be available to a user in a certain user role. In this article, we’ll take a look at how you can use these functions to determine what content is available for any given user on your WordPress website.
Using these functions, you can easily decide what content, functionality, or actions should be available to a user in a certain user role.
There is no official WordPress function for giving a user a specific WordPress user role, so you need to write your own. Here’s an example custom function that you can use to check if a user can view a page or post.
You will need to add this short piece of code to the functions.php file in your active child theme or you could use a Snippets plugin to add the code: