0

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?

  • this is a tough one to debug, honestly. is your WP installation in a subfolder? When you log in, check your console and see if WP is setting cookies. usually `wordpress_logged_in`, when you log in. Once you find it, check the location to the cookie, make sure the path is correct and does not contain double `//`, or perhaps, improper pathing. check `bloginfo('home')`, is that the correct path to your site? Also `var_dump($_COOKIE)` to check for `wordpress_logged_in` – Ohgodwhy Mar 30 '13 at 22:44

2 Answers2

1

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
  • 21
  • 3
0

@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.

Pons
  • 1,747
  • 1
  • 13
  • 19