Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@kellenmace
Created September 20, 2016 20:43
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kellenmace/5dcc82b722c59c79d9b8f98b43d0e4e9 to your computer and use it in GitHub Desktop.
Save kellenmace/5dcc82b722c59c79d9b8f98b43d0e4e9 to your computer and use it in GitHub Desktop.
Get User's First and Last Name in WordPress
<?php
/**
* Get user's first and last name, else just their first name, else their
* display name. Defalts to the current user if $user_id is not provided.
*
* @param mixed $user_id The user ID or object. Default is current user.
* @return string The user's name.
*/
function km_get_users_name( $user_id = null ) {
$user_info = $user_id ? new WP_User( $user_id ) : wp_get_current_user();
if ( $user_info->first_name ) {
if ( $user_info->last_name ) {
return $user_info->first_name . ' ' . $user_info->last_name;
}
return $user_info->first_name;
}
return $user_info->display_name;
}
@samar241
Copy link

samar241 commented Nov 7, 2019

What's the shortcode to display the name?
Thanks...

@kellenmace
Copy link
Author

@samar241 If you want to use this as a shortcode, you would need to register a new shortcode for that purpose. Here's an example:

function km_register_name_shortcode() {
    add_shortcode('current_user_name', 'km_get_users_name');
}
add_action('init', 'km_register_name_shortcode');

If you want the shortcode to accept a user ID as an argument, then you would need to tweak that code to do so. Details are here: https://developer.wordpress.org/plugins/shortcodes/basic-shortcodes/

Best of luck!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment