WordPress at a glance

wp_get_current_user() WP 2.0.3

Retrieve the current authorized user data (WP_User object).

This is a pluggable function, and it can be replaced by a plugin. It means that this function is defined (works) only after all plugins are loaded (included), but before this moment this function has not defined. Therefore, you cannot call this and all functions depended on this function directly from a plugin code. They need to be called on plugins_loaded hook or later, for example on init hook.

Function replacement (override) — in a plugin you can create a function with the same name, then it replace this function.

✈ 1 time = 0.00001s = speed of light | 50000 times = 0.03s = speed of light

No Hooks.

Return

WP_User. Current WP_User instance.

If the user is not authorized, an empty object will be returned! I.e. you should not use this function to determine if the user is authorized!

if( wp_get_current_user() ){
	echo 'It will always be printed!';
}

// You need to do so:
if( wp_get_current_user()->exists() ){
	echo 'Authorized!';
}

// Or so: 
if( is_user_logged_in() ){
	echo 'Authorized!';
}

Usage

wp_get_current_user();

Examples

#1 Determine whether the user is authorized

Determine whether the user is logged-in (authorized). If the user doesn't exist, his ID will be equal to 0:

$current_user = wp_get_current_user();
if( $current_user->ID ){
	// Authorized.
}
else {
	// Unauthorized.
}

But it's better to use is_user_logged_in() instead.

#2 Get current user data

And display it.

$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 'Display Name: '     . $current_user->display_name   . '<br />';
echo 'ID: '               . $current_user->ID             . '<br />';

Notes

  • See: _wp_get_current_user()
  • Global. WP_User. $current_user Checks if the current user is set.

Changelog

Since 2.0.3 Introduced.

Code of wp get current user: wp-includes/pluggable.php WP 5.2.2

<?php
function wp_get_current_user() {
	return _wp_get_current_user();
}

Related Functions

From tag: Users (_user)

More from category: Other

No comments
    Hello, !     Log In . Register