假设用户已将其化身保存为附件的ID,则将其存储在用户meta中作为字段field_with_custom_avatar_id
, 如果保存了值,则可以执行此操作以显示该附件:
add_filter( \'get_avatar\', \'slug_get_avatar\', 10, 5 );
function slug_get_avatar( $avatar, $id_or_email, $size, $default, $alt ) {
//If is email, try and find user ID
if( ! is_numeric( $id_or_email ) && is_email( $id_or_email ) ){
$user = get_user_by( \'email\', $id_or_email );
if( $user ){
$id_or_email = $user->ID;
}
}
//if not user ID, return
if( ! is_numeric( $id_or_email ) ){
return $avatar;
}
//Find ID of attachment saved user meta
$saved = get_user_meta( $id_or_email, \'field_with_custom_avatar_id\', true );
if( 0 < absint( $saved ) ) {
//return saved image
return wp_get_attachment_image( $saved, [ $size, $size ], false, [\'alt\' => $alt] );
}
//return normal
return $avatar;
}
或者,如果它保存为图像的URL,则在用户元字段中
field_with_custom_avatar
-
add_filter( \'get_avatar\', \'slug_get_avatar\', 10, 5 );
function slug_get_avatar( $avatar, $id_or_email, $size, $default, $alt ) {
//If is email, try and find user ID
if( ! is_numeric( $id_or_email ) && is_email( $id_or_email ) ){
$user = get_user_by( \'email\', $id_or_email );
if( $user ){
$id_or_email = $user->ID;
}
}
//if not user ID, return
if( ! is_numeric( $id_or_email ) ){
return $avatar;
}
//Find URL of saved avatar in user meta
$saved = get_user_meta( $id_or_email, \'field_with_custom_avatar\', true );
//check if it is a URL
if( filter_var( $saved, FILTER_VALIDATE_URL ) ) {
//return saved image
return sprintf( \'<img src="%" alt="%" />\', esc_url( $saved ), esc_attr( $alt ) );
}
//return normal
return $avatar;
}