Create a function that returns the currently logged-in user's data, like ID, username, email address, nickname, roles, etc. Return the data in an array.

Home » Snippets » Create a function that returns the currently logged-in user's data, like ID, username, email address, nickname, roles, etc. Return the data in an array.
0

Created with:

Visibility: 

public

Creator: Haugendaus

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project
					<?php

/**
 * Retrieve the currently logged-in user's data.
 *
 * @return array User data including ID, username, email address, nickname, and roles.
 */
function wpturbo_get_current_user_data() {
    $current_user = wp_get_current_user();
    
    if ( $current_user && $current_user->ID ) {
        $user_data = array(
            'ID' => $current_user->ID,
            'username' => $current_user->user_login,
            'email' => $current_user->user_email,
            'nickname' => $current_user->user_nicename,
            'roles' => $current_user->roles,
        );
        
        return $user_data;
    }
    
    return array(); // Return an empty array if user data is not available.
}
				

In this code, we define a new function wpturbo_get_current_user_data() that retrieves the currently logged-in user's data using the wp_get_current_user() function. We then check if the current user exists and has an ID. If so, we create an array with the user's ID, username, email address, nickname, and roles. Finally, we return the user data array. If the user data is not available, an empty array is returned.

You can use this function wherever you need to access the currently logged-in user's data. For example, you can call wpturbo_get_current_user_data() and store the returned array in a variable to use the user data in your plugin or theme.

Register an account to save your snippets or go Pro to get more features.