WordPress как на ладони
rgbcode is looking for WordPress developers. Очень Удобный и Быстрый Хостинг для сайтов на WordPress. Пользуюсь сам и вам рекомендую!

wp_get_current_user()WP 2.0.3

Получает данные о текущем авторизованном пользователе (объект WP_User). Устанавливает пользователя, если не установлен.

Устанавливает текущего пользователя, при первом вызове функции, далее результат запоминается в глобальную переменную $current_user. Если пользователь не авторизован, то устанавливается пустой пользователь wp_set_current_user( 0 ).

Функцию можно использовать начиная с события plugins_loaded. Если вызвать её раньше, то получим fatal error.

Вернет 0 если используется в неавторизованном REST запросе. Один из способов авторизовать REST запрос - это указать nonce код. Подробнее про авторизацию в REST.

Если очень нужно вызвать функцию до события plugins_loaded, то нужно предварительно подключить зависимости. Однако делать это нужно с полным пониманием того, как работает авторизация.

// зависимости
wp_cookie_constants();
require ABSPATH . WPINC . '/pluggable.php';

$cuser = wp_get_current_user(); //> WP_User object

Используйте get_current_user_id(), когда нужно получить ID пользователя.

$current_user_id = get_current_user_id();
$current_user = wp_get_current_user();

ID текущего пользователя определяется функциям:

Pluggable функция — эту функцию можно заменить из плагина. Это значит, что она будет работать (подключается) только после подключения всех плагинов, а до этого момента функция еще не определена... Поэтому нельзя вызывать эту и зависящие от неё функции прямо из кода плагина. Их нужно вызывать через хук plugins_loaded или позднее, например хук init.

Замена функции (переопределение) — в must-use или обычном плагине можно создать функцию с таким же названием, тогда она заменит текущую функцию.

1 раз — 0.00001 сек (скорость света) | 50000 раз — 0.03 сек (скорость света)

Хуков нет.

Возвращает

WP_User. Объект WP_User.

WP_User Object
(
	[data] => stdClass Object
		(
			[ID] => 1
			[user_login] => alex
			[user_pass] => $P$B/NlqweHhtrD6HthgjF5UYOMdT77.x0
			[user_nicename] => alex-1
			[user_email] => alex@gmail.ru
			[user_url] =>
			[user_registered] => 2010-03-26 09:27:40
			[user_activation_key] => 1987530484:$P$ByO33dFHn3aWu.Pe4Uw.MUhGGT59zc1
			[user_status] => 1646545990
			[display_name] => Alex
		)

	[ID] => 1
	[caps] => Array
		(
			[administrator] => 1
		)

	[cap_key] => wp_capabilities
	[roles] => Array
		(
			[0] => administrator
		)

	[allcaps] => 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
			[promote_users] => 1
			[edit_theme_options] => 1
			[delete_themes] => 1
			[export] => 1
			[edit_artic] => 1
			[read_artic] => 1
			[delete_artic] => 1
			[edit_artics] => 1
			[edit_others_artics] => 1
			[publish_artics] => 1
			[read_private_artics] => 1
			[delete_artics] => 1
			[delete_private_artics] => 1
			[delete_published_artics] => 1
			[delete_others_artics] => 1
			[edit_private_artics] => 1
			[edit_published_artics] => 1
			[manage_woocommerce] => 1
			[view_woocommerce_reports] => 1
			[edit_product] => 1
			[read_product] => 1
			[delete_product] => 1
			[edit_products] => 1
			[edit_others_products] => 1
			[publish_products] => 1
			[read_private_products] => 1
			[delete_products] => 1
			[delete_private_products] => 1
			[delete_published_products] => 1
			[delete_others_products] => 1
			[edit_private_products] => 1
			[edit_published_products] => 1
			[manage_product_terms] => 1
			[edit_product_terms] => 1
			[delete_product_terms] => 1
			[assign_product_terms] => 1
			[edit_shop_order] => 1
			[read_shop_order] => 1
			[delete_shop_order] => 1
			[edit_shop_orders] => 1
			[edit_others_shop_orders] => 1
			[publish_shop_orders] => 1
			[read_private_shop_orders] => 1
			[delete_shop_orders] => 1
			[delete_private_shop_orders] => 1
			[delete_published_shop_orders] => 1
			[delete_others_shop_orders] => 1
			[edit_private_shop_orders] => 1
			[edit_published_shop_orders] => 1
			[manage_shop_order_terms] => 1
			[edit_shop_order_terms] => 1
			[delete_shop_order_terms] => 1
			[assign_shop_order_terms] => 1
			[edit_shop_coupon] => 1
			[read_shop_coupon] => 1
			[delete_shop_coupon] => 1
			[edit_shop_coupons] => 1
			[edit_others_shop_coupons] => 1
			[publish_shop_coupons] => 1
			[read_private_shop_coupons] => 1
			[delete_shop_coupons] => 1
			[delete_private_shop_coupons] => 1
			[delete_published_shop_coupons] => 1
			[delete_others_shop_coupons] => 1
			[edit_private_shop_coupons] => 1
			[edit_published_shop_coupons] => 1
			[manage_shop_coupon_terms] => 1
			[edit_shop_coupon_terms] => 1
			[delete_shop_coupon_terms] => 1
			[assign_shop_coupon_terms] => 1
			[edit_shop_webhook] => 1
			[read_shop_webhook] => 1
			[delete_shop_webhook] => 1
			[edit_shop_webhooks] => 1
			[edit_others_shop_webhooks] => 1
			[publish_shop_webhooks] => 1
			[read_private_shop_webhooks] => 1
			[delete_shop_webhooks] => 1
			[delete_private_shop_webhooks] => 1
			[delete_published_shop_webhooks] => 1
			[delete_others_shop_webhooks] => 1
			[edit_private_shop_webhooks] => 1
			[edit_published_shop_webhooks] => 1
			[manage_shop_webhook_terms] => 1
			[edit_shop_webhook_terms] => 1
			[delete_shop_webhook_terms] => 1
			[assign_shop_webhook_terms] => 1
			[ure_edit_roles] => 1
			[ure_create_roles] => 1
			[ure_delete_roles] => 1
			[ure_create_capabilities] => 1
			[ure_delete_capabilities] => 1
			[ure_manage_options] => 1
			[ure_reset_roles] => 1
			[edit_blocks] => 1
			[edit_others_blocks] => 1
			[publish_blocks] => 1
			[read_private_blocks] => 1
			[read_blocks] => 1
			[delete_blocks] => 1
			[delete_private_blocks] => 1
			[delete_published_blocks] => 1
			[delete_others_blocks] => 1
			[edit_private_blocks] => 1
			[edit_published_blocks] => 1
			[create_blocks] => 1
			[administrator] => 1
		)

	[filter] =>
	[site_id:WP_User:private] => 1
)

Если пользователь не авторизован, вернет пустой объект! Поэтому НЕЛЬЗЯ проверять авторизован ли пользователь через эту функцию:

if( wp_get_current_user() ){
	echo 'эта строка будет выводиться всегда!';
}

// Нужно так:
if( wp_get_current_user()->exists() ){
	echo 'Авторизован!';
}

// или так:
if( is_user_logged_in() ){
	echo 'Авторизован!';
}

Использование

wp_get_current_user();

Примеры

3

#1 Получим данные текущего пользователя

Выведем на экран различные данные о текущем авторизованном пользователе:

$current_user = wp_get_current_user();

echo 'Username: '         . $current_user->user_login     . '<br />';
echo 'email: '            . $current_user->user_email     . '<br />';
echo 'first name: '       . $current_user->user_firstname . '<br />';
echo 'last name: '        . $current_user->user_lastname  . '<br />';
echo 'Отображаемое имя: ' . $current_user->display_name   . '<br />';
echo 'ID: '               . $current_user->ID             . '<br />';
2

#2 Проверим авторизован ли пользователь на сайте

Проверим авторизован (залогинен) ли пользователь. Если пользователя не существует, его ID будет равен 0:

$current_user = wp_get_current_user();
if( $current_user->exists() ){
	// Авторизован.
}
else {
	// Не авторизован.
}

Но лучше использовать для этих целей is_user_logged_in().

Заметки

Список изменений

С версии 2.0.3 Введена.

Код wp_get_current_user() WP 6.4.3

function wp_get_current_user() {
	return _wp_get_current_user();
}
16 комментариев
Полезные 3 Все
    Войти