How to display a user’s avatar by user-id in wordpress via 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, and it displays the current logged-in user, like this:

<?php
function shortcode_user_avatar() {
    if(is_user_logged_in()) { // check if user is logged in
        global $current_user; // get current user's information
        get_currentuserinfo();
        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( 'http://1.gravatar.com/avatar/ad524503a11cd5ca435acc9bb6523536?s=64', 24 );
    }
}
add_shortcode('display-user-avatar','shortcode_user_avatar');
?>

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"]

Read More

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

Related posts

1 comment

  1. I’ve already solve this problem, here is the code:

    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  
                                                           }
    add_shortcode('avatar','shortcode_user_avatar');
    

    Just paste it to theme’s functions.php and enter the shortcode [avatar id="xxx"], and replace “xxx” to the user id.

    It’s actually my first shortcode, and I’m really happy that it’s working!

Comments are closed.