How do I display logged-in username IF logged-in? site:wordpress.stackexchange.com

To display the logged-in username on a WordPress website, you can use the following code snippet:

<?php
if (is_user_logged_in()) {
    $current_user = wp_get_current_user();
    echo 'Logged in as: ' . $current_user->user_login;
}
?>

Here is an explanation for each step:

  1. Check if the user is logged in: The is_user_logged_in() function is used to check if the user is currently logged in. It returns true if the user is logged in and false otherwise.

  2. Get the current user: If the user is logged in, we use the wp_get_current_user() function to retrieve the current user object, which contains information about the logged-in user.

  3. Display the username: Finally, we can access the username of the current user using the $current_user->user_login property and display it using the echo statement.

Make sure to place this code snippet in the appropriate template file or in a custom WordPress plugin or theme file.