1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

[Docs] Showing User Avatars

Discussion in 'Design and Layout' started by Nick, Jan 10, 2010.

  1. Nick

    Nick Well-Known Member

    Including user avatars in your theme is easy if you know the ID number of the user you want to show.

    First, here are three ways to get a user's ID number:
    PHP:
    $id $h->currentUser->id// this holds the ID of the person viewing the page
    $id $h->getUserIdFromName($username); // provide the username
    $id $h->getUserIdFromEmail($email); // provide the email address
    Next, you need to set the avatar, like this:

    PHP:
    $h->setAvatar($id$size$rating);

    $size: defaults to 32 pixels
    $rating: g, pg, r, or x. The default is "g" (safe for kids).

    Examples:

    PHP:
    $h->setAvatar($id); // defaults to 32 pixels with rating "g".
    $h->setAvatar($id16); // 16 pixels with rating "g".
    $h->setAvatar($id16'pg'); // 16 pixels with rating "pg".
    $h->setAvatar($id0'x'); // default 32 pixels with rating "x";
    To show the avatar, you have three choices:

    PHP:
    echo $h->getAvatar(); // displays the avatar, i.e. IMG tags only
    echo $h->linkAvatar(); // displays the avatar linked to the user's profile
    echo $h->wrapAvatar(); // displays the avatar linked and wrapped in a div with class "avatar_wrapper"
    Before you show an avatar, it's a good idea to check if an avatar plugin (e.g. Gravatar) is currently active:

    PHP:
    if($h->isActive('avatar')) {
        
    $h->setAvatar($h->currentUser->id16);
        echo 
    $h->linkAvatar();
    }
    Advanced usage:

    The above code works fine for a handful of avatars, but it might be a bit slow with the Gravatar plugin because Gravatar requires a user email and we don't provide that from the template. Instead, the Avatar class in Hotaru's libs directory pulls the user details for each user from the database (if not cached) and the Gravatar plugin then gets the email address from those.

    If you already have the user's id, username and email address, a faster way (although more wordy) is to get the avatar like this:

    PHP:
    $avatar = new Avatar($h);
    $avatar->user_id $id;
    $avatar->user_email $email;
    $avatar->user_name $name;
    $avatar->size 16;  // optional - defaults to 32 if not used
    $avatar->rating "pg"// optional - defaults to "g" if not used
    $avatar->setVars($h); // this is so plugins can access the properties
    echo $avatar->getAvatar($h); // or linkAvatar($h) or wrapAvatar($h)
    I would recommend using code like that if you want to show a block filled with user avatars.
     

Share This Page