不得不说 WordPress 确实很强大,但是随着 WordPress 应用的广泛性和快速发展,其应用范围也越来越广,从当初的博客,到企业网站,再到现在的社交性的网站,越来越受到人们的欢迎。很多的功能方面有些时候也并不是适合与每一个站点,而 WordPress 默认情况下使用的是 Gravatar 头像,但是使用略有不便,比如我们国内需要翻墙才能注册这个头像,普通的网民或者用户可能很难操作吧!

Gravatar

而在近期子凡做泪雪旗下网站间整合的时候,就需要把各个网站间用户的头像全部统一,而对于在 WordPress 系统本身就拥有一套头像体系的情况下,我们只能选择替换。之所以能使用替换,也是源自于 WordPress 提供了良好的接口。多的就不说了,直接上代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//头像重置到 i.leixue.com (last update 2018/11/12)
add_filter( 'get_avatar' , 'my_custom_avatar' , 1 , 5 );
function my_custom_avatar( $avatar, $id_or_email, $size, $default, $alt) {
	if (filter_var($id_or_email, FILTER_VALIDATE_EMAIL)) {//判断是否为邮箱
		$email = $id_or_email;//用户邮箱
		$user = get_user_by( 'email', $email );//通过邮箱查询用户信息
	}else{
		$uid = (int) $id_or_email;//获取用户 ID
		$user = get_user_by( 'id', $uid );//通过 ID 查询用户信息
	}
 
	//$user_login = $user->user_login;//用户名
	$email = $user->user_email;//用户邮箱
	$alt = $user->user_nicename;//用户昵称
	if(get_comment_author_email( $comment )){//通过评论获取邮箱
		$email = get_comment_author_email( $comment );
		$alt = get_comment_author( $comment );
	}
 
    $avatar = "https://i.leixue.com/avatar.php?email=".$email;
    $avatar = "<img alt='{$alt}' src='{$avatar}' class='avatar avatar-{$size} photo' height='{$size}' width='{$size}' />";
 
    return $avatar;
}

直接把以上代码粘贴在主题 functions.php 中即可。以上代码是子凡在开发泪雪建站时所使用的,如果你有一套自己完善的头像体系,也可以使用这样的方法调用自己网站的头像。

另外泄漏一个秘密,如果你直接使用上面代码,你网站的用户头像就接入到泪雪用户中心来啦!只要你网站的用户在泪雪个人中心(i.leixue.com)注册帐户并上传了自己的头像,都可以完美的调用哦!

嘿嘿,有没有很高科技的样子?

更多关于WordPress优化及疑问可以添加QQ群:255308000

除非注明,否则均为泪雪博客原创文章,禁止任何形式转载

本文链接:https://zhangzifan.com/wordpress-custom-user-avatar.html

留言评论

登录 后留言