A shortcode to retrieve user data

Sometimes you need to show logged-in user details (nickname, email address, first name, last name or ID).

You can let a plugin do the job, or you can add some lines of code to your functions.php.

If you decide to write your code, you could find efficient to create a shortcode so that the site admin can add data anywhere is necessary.

Now suppose you want to create the shortcode [userdata].

And suppose that the shortcode shoud print only one of the many fields related to the user profile. In this case you should pass to the shortcode one of the following attributes:

  • user_login
  • user_email
  • user_firstname
  • user_lastname
  • display_name
  • ID

Here is your code:


// create [userdata] shortcode
function get_current_userdata_cb( $atts ){
    if ( is_user_logged_in() ) { 
        // get the current user
        $cu = wp_get_current_user();

        switch ( $atts[0] ) {
            case 'user_login':
                return $cu->user_login;
                break;
            case 'user_email':
                return $cu->user_email;
                break;
            case 'user_firstname':
                return $cu->user_firstname;
                break;
            case 'user_lastname':
                return $cu->user_lastname;
                break;
            case 'display_name':
                return $cu->display_name;
                break;
            case 'ID':
                return $cu->ID;
                break;
            default:
                return $cu->user_login;
                break;
        }

    }else{
        return '';
    }
}
add_shortcode( 'userdata', 'get_current_userdata_cb' );

If the user is logged-in (is_user_logged_in), a new instance of WP_User class is created (wp_get_current_user).

The first attribute which has been passed to the shortcode (atts[0]) is compared with all possible values of WP_User properties ($cu->{$prop}).
When a correspondence is found, the function returns the value of the property and the execution is stopped.

Save your functions.php and insert the shortcode [userdata display_name] in your content…