How to display avatar by user-id using shortcode?

I've looked through lots of documents, few of them showed a shortcode to display the avatar using user_id.
The closest one is from Github, but it just displays the current logged-in user, like this:

function shortcode_user_avatar() {
    if(is_user_logged_in()) { // check if user is logged in
        global $current_user; // get current user's information
        return get_avatar( $current_user -> ID, 24 ); // display the logged-in user's avatar
    else {
      // if not logged in, show default avatar. change URL to show your own default avatar
        return get_avatar( '', 24 );

But this isn't enough, what I want is to add a parameter for me to choose the userid, and it will end like this:

[display-user-avatar id="user-id"]

Can anybody show me the way to make it? Thanks!

  • Adam Czajczyk

    Hello Edi,

    I hope you're well today and thank you for your question!

    As you can see in the code that you posted here, the "get_avatar()" function takes user ID as a parameter. In this code, the currently logged in user ID is passed to it so all you need to do is pass specific user ID. As a shortcode can take parameters (take a look here please) this should be even simpler than the one you shared:

    function shortcode_user_avatar($atts) {
    	$userID = esc_html($atts['id']); // read user ID from shortcode attribute
    	$userAvatar = get_avatar( $userID, 24 ); //get avatar for that user
    	if ($userAvatar) return $userAvatar; // returns avatar or nothing if avatars are turned off


    [display-user-avatar id="X"]

    where "X" is a user ID.

    I hope that helps!
    Best regards,

  • Edi

    Hi Adam,
    Really appreciate your quick response! That could really help a lot!
    And I've come up with a simpler code, and it also works:

    function shortcode_user_avatar($atts, $content = null) {
    extract( shortcode_atts(
                    array('id' => '0',), $atts
    return get_avatar( $user_id, 96 ); // display the specific user_id's avatar

    Just a note, it's my first shortcode, and it was thrilling when I saw it works!

Thank NAME, for their help.

Let NAME know exactly why they deserved these points.

Gift a custom amount of points.