2

The following custom avatar functions works fine, but I get the following notice

"Trying to get property of non-object in..."

The notice says the problem is on the last part of the function I pasted here - I marked it in the code (look for <-- Notice mentions this line)

Any idea how to fix this? I am stuck...

function test_get_avatar($avatar, $id_or_email, $size, $default, $alt) {
if (!is_numeric($id_or_email)) {
    if (is_string($id_or_email)) {
        $user = get_user_by('email', $id_or_email);
        $id_or_email = $user->ID;
    } else if (is_object($id_or_email)) {
        if (!empty($id_or_email->ID)) {
            $id_or_email = $id_or_email->ID;
        }

        if (!empty( $id_or_email->comment_author_email)) {
            $user = get_user_by('email', $id_or_email->comment_author_email);
            $id_or_email = $user->ID; <-- Notice mentions this line
        }
    }
}

$avatar_id = get_user_meta($id_or_email, 'nicobartes_user_avatar', true);
...
JakeParis
  • 11,056
  • 3
  • 42
  • 65
evavienna
  • 1,059
  • 11
  • 29
  • `$user` is not an object.... so by definition (in PHP) it can not contain an attribute referenced as `ID`. Where is `$user` set? – Martin Jan 12 '18 at 21:22
  • @martin - everthing is possible but im not able to solve my problem with your url to the Reference page... I already searched similar questions and found nothing so far. So i need help. Would be awesome if someone helps me out. best – evavienna Jan 12 '18 at 21:31
  • Are you seriously telling me you [read this answer](https://stackoverflow.com/a/26572398/3536236) and you still don't know how to solve your issue? – Martin Jan 12 '18 at 21:36
  • Now i did :) thx – evavienna Jan 12 '18 at 21:40
  • 1
    Sorry, I should have linked that answer directly in the first instance, rather than just the question – Martin Jan 12 '18 at 22:20
  • 1
    Possible duplicate of [Reference - What does this error mean in PHP?](https://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php) – Félix Adriyel Gagnon-Grenier Jan 12 '18 at 22:37

2 Answers2

2

Yes, because get_user_by() can fail and return false. At that point you won't have a wp user object. A test around this code would be:

if ($user = get_user_by('email', $id_or_email->comment_author_email)) {
    $id_or_email = $user->ID; 
} else {
    //Whatever you want to do when this lookup fails
    $id_or_email = 0;
}
gview
  • 14,876
  • 3
  • 46
  • 51
0

When you run

$user = get_user_by('email', $id_or_email->comment_author_email);

You should check the value of $user before attempting to get the id on the next line. According to the Wordpress docs, it could potentially be false if no user is found.

JakeParis
  • 11,056
  • 3
  • 42
  • 65