How to Display Username In WooCommerce

WooCommerce Display Username

Are you looking for a quick and easy way to create a custom WooCommerce user profile and want to display the username?  In this post, I will share with you an excellent solution that will quickly help you to display your username in WooCommerce.

I run into the same problem when I was customizing WooCommerce, I came up with a WooCommerce display username code snippet that you too can use in your custom WooCommerce development.

WooCommerce Display Username

To display the WooCommerce username of the logged-in user you need to first check if the user is logged in then you get the details of the user who is logged in and display. The following is a code snippet that I use to display the username of the logged-in user :

 

global $current_user;

wp_get_current_user();

if ( is_user_logged_in() ) {

echo 'Username: ' . $current_user->user_login .
"\n"; echo 'User display name: '
. $current_user->display_name . "\n";

}

 

You can also create a shortcode that you can use to display the username using the code snippet below :

function njengah_display_logged_user( $atts ) {

global $current_user, $user_login;
get_currentuserinfo();
add_filter('widget_text', 'do_shortcode');
if ($user_login)
return 'Welcome ' . $current_user->display_name . '!';
else
return '<a href="' . wp_login_url() . ' ">Login</a>';

}
add_shortcode( 'njengah_logged_in_user_wc', 'njengah_display_logged_user' );


Now let us put these code snippets to the test.

I have added the code snippet above to the functions.php to add the shortcode that displays the name of the logged-in user.

When you have created the shortcode to display the name of the logged-in user, you can now use the shortcode anywhere in the pages, posts, and templates:

WooCommerce Display Username

When you publish the page, you should see the frontend display of the WooCommerce logged-in username as shown in the image below :

WooCommerce Display Username

Conclusion

In this post, we have looked at how to display a username in WooCommerce, as you can see there are two steps involved in displaying the username using a shortcode.

You can easily and quickly use this solution in your WooCommerce theme or plugin development.

Just in case you are stuck, I am always ready to help you implement this solution and also to further customize it to fit your specific needs.

Similar Articles