简体   繁体   中英

User Avatar Wordpress Php

I'm trying to show anonymous icon when users are not logged in and show user avatar when they are logged in ... here's what I got for code (wordpress install btw)

<div id="useravatar">
<?php
global $current_user;
if (!is_user_logged_in()) {
echo "<img src='"http://www.curious-howto.com/images/anonymous.jpg"'/>";
}
else { get_currentuserinfo();
   echo get_avatar( $current_user->ID, 32 ); }
?>
</div>

but this is not working...

Could someone point out what I'm doing wrong?

Since there are no answers, and this pops up on Google ...

There are double quotation marks which shouldn't be there in the img tag. This breaks the PHP.

echo "<img src='"http://www.curious-howto.com/images/anonymous.jpg"'/>";

should be

echo "<img src='http://www.curious-howto.com/images/anonymous.jpg'/>";

@Guyra pointed out the quotation error and I've also noted that the get_currentuserinfo is deprecated since WordPress 4.5.

You can hook the get_avatar function and modify the output in your functions.php file. Using get_avatar is better and it will retrieve user avatar if the user is known, and gray man if it isn't. By hooking the function you can modify it and change how it works with unknown people:

add_filter( 'get_avatar','get_custom_avatar' , 10, 5 );
function get_custom_avatar($avatar, $author, $size, $default, $alt) {
  if(stristr($author,"@")) $autore = get_user_by('email', $author);
    else $autore = get_user_by('ID', $author);

  if (isset($autore->ID) && $autore->ID > 0) {
      // known people
      return $avatar;
  } else {
      // unknown user
      $avatar = "http://www.curious-howto.com/images/anonymous.jpg";
      return "<img class='avatar' alt=\"".$alt."\" src='".$avatar."' width='".$size."' />";
 }

}

Got this code and modified from here , there are also variations to get generated avatars from a different service instead of Gravatar.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM