How to Get the ID of Current Logged in User from WordPress!

2.1818181818182 from 5
from 11 user
(Rate this post)
How to Get the ID of Current Logged in User from WordPress!

Performing features of an interactive website requires the ID of the current interacting user. WordPress has a function responsible for getting the current user's ID in W, which is helpful when it comes to developing interactive features for users. This tutorial is about retrieving the current user's ID if the visitor is logged in.

Introducing get_current_user_id function

Since WordPress v2.0.3, developers can use a dedicated function to retrieve the current user’s ID. Before that, they need to get the whole user object first, then extract the ID from it.

get_current_user_id() function introduced to help developers write fewer lines of code when they want to retrieve the current user’s ID.

get_current_user_id function syntax

You do not need to specify anything for this function to get the current user’s ID. The function will detect the current user itself.

get_current_user_id()

After execution, the get_current_user_id() returns the current user’s ID, or if the user is not logged in, it will return 0.

get_current_user_id function example

If this example, we’ll check the current user ID, and if it is equal to what we determined (ID 1), a text message will be printed on the screen:

Another way to get the current user’s ID (Not Recommended for cleaner code)

The get_current_user_id() function is running wp_get_current_user() under the hood. You can directly get the current user with all information, then try to extract the ID from the returned WP_User object.

For a cleaner code, you better use the get_current_user_id().

If you are still interested, you can get the current user’s object from WP and then try to extract the ID from it using this code:

$targetUserId=1;

//get the current user as WP_User object
$currentUser = wp_get_current_user();

//check if current user is available with isset() and then check if it's our targeted user
if(isset($currentUser->ID) && $currentUser->ID === $targetUserId){
	//current user id is matching our target user's id
	echo "Wellcome to our website, You are a special customer to us";
}

What do you think about "How to Get the ID of Current Logged in User from WordPress!"?

Your rating submit was successfull.

Your rating submit was not successfull.

Menu