0

I'm creating a matrimonial website. I want to set the user avatar based on the gender(I have a custom_user_meta for the user's gender) But I don't understand how to get the "user id" in order to use the meta data "user_meta_gender"(to find out if the user is male or female).

P.S: I'm not using buddypress, I'm using a plugin named Profile Builder Pro Also get_current_user_id does not work since it retrieves only the LOGGED IN users ID.

``This is the code I used in my functions.php:

function dynamic_user_gravatar($current_dp){

$id = get_the_ID();  //This is where I want to figure out a way to find the user id, this won't work.
$key = "user_gender";
$single = true;

$gender = get_user_meta($id, $key, $single);
if($gender == 'Male'){
    $myavatar = 'http://localhost:81/matrimony/wp-content/uploads/2020/04/groom.png';
}else{
    $myavatar = 'http://localhost:81/matrimony/wp-content/uploads/2020/04/bride.png';
 }
 return $myavatar;
}

add_filter( 'get_avatar', 'dynamic_user_gravatar');

Additionally I figured out that I can return the relevant users avatar by the parameter "$current_dp", in case if there is no direct method to get the user_id can we user $current_dp to retrieve the user_id from the avatar? ``

  • Did you try get_current_user_id? – Jos Apr 17 at 13:35
  • @Jos What happens when I use get_current _user_id is, it takes the logged in users id and changes the avatar based on it, for an example if the logged in user is FEMALE all other users avatars are changed to BRIDE.PNG – shimii Apr 17 at 13:43
  • The get_avatar hook is applied with apply_filters('get_avatar', $avatar, $id_or_email, $args['size'], $args['default'], $args['alt'], $args ). So your function declaration should be function dynamic_user_gravatar ($avatar, $id_or_email); then you can use $id_or_email in your function body. – Jos Apr 17 at 14:05
  • @Jos Thank You very much for the answer :) – shimii Apr 17 at 14:15
0

I managed to come up with the answer :D Thanks to @Jos

function ht1_change_avatar($args, $id_or_email) {
    $gender = get_user_meta($id_or_email, 'user_gender', true);
    if($gender=='Male'){
        $myavatar = 'http://localhost:81/matrimony/wp-content/uploads/2020/04/groom.png';
    }else{
        $myavatar = 'http://localhost:81/matrimony/wp-content/uploads/2020/04/bride.png';
    }
    $args['url'] = $myavatar;
    return $args;
}
add_filter('get_avatar_data', 'ht1_change_avatar', 100, 2);
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.