Custom Field Repeating When Using foreach

I'm trying to display user avatars by login user name using custom fields like this -

And here's the code -

function user_avatar() {

        $name  = get_post_meta( get_the_ID(), 'user_name', true );

        $users = get_user_by( 'login', $name  );

        foreach( (array) $users as $user )

        authors();
}


function authors() {

    $gravatar = get_avatar( $user-user_email , 32 );

    echo $gravatar;

}

However, this code repeats avatars in addition to the only one i want printed.

I need to print only the avatars where's there's a custom field value based on username.

Topic gravatar user-meta avatar users custom-field Wordpress

Category Web


if you want to use multiple users, if you will add usernames comma separated in custom field. try below code.

function user_avatar() {
    $user = "";
    $names  = get_post_meta( get_the_ID(), 'user_name', true );
    $user_names = array_map('trim', explode(',', $names));
    if(!empty($user_names))
    {
       foreach ($user_names as $key => $user_name) 
       {
          $user = get_user_by( 'login', $user_name  );
          if($user)
          {
              $gravatar = get_avatar( $user->user_email , 32 );
              echo $gravatar;
          }
       }
    }
}

Edit : I also tried -

$names  = get_post_custom_values( 'user_name' );

I tested this when using the same custom field key user_name with different login usernames for each user.

if you want to use get_post_custom_value(); try below

function user_avatar() {
        $user = "";
        $names  = get_post_custom_values( 'user_name', get_the_ID() );
        if(!empty($names))
        {
           foreach ($names as $key => $user_name) 
           {
              $user = get_user_by( 'login', $user_name  );
              if($user)
              {
                  $gravatar = get_avatar( $user->user_email , 32 );
                  echo $gravatar;
              }
           }
        }
    }

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.