01
2019
09

WordPress随机头像

众所周知的,WordPress是采用Gravatar作为用户的头像的,但是大多数人是没有使用Gravatar头像的,显示出来的就是默认的头像,很丑。

所以这篇教程来教一下如何WordPress为没有Gravatar头像的用户加载随机头像。

在主题的functions.php中加入以下代码:

add_filter('get_avatar', 'inlojv_custom_avatar', 10, 5);
function inlojv_custom_avatar($avatar, $id_or_email, $size, $default, $alt) {
    global $comment,
    $current_user; // $id_or_email的值:后台右上角登录用户头像为id,其他为邮箱,下面做一个判断 $current_email = is_int($id_or_email) ? get_user_by( 'ID', $id_or_email )->user_email : $id_or_email; $email = !empty($comment->comment_author_email) ? $comment->comment_author_email : $current_email ; $random_avatar_arr = array( '//wx1.sinaimg.cn/square/6b002b97gy1ffs6ulm8ojj20690690sl.jpg', '//wx1.sinaimg.cn/square/6b002b97gy1ffs6ulfp76j2069069t8p.jpg', '//wx1.sinaimg.cn/square/6b002b97gy1ffs6ukuo5dj2069069a9w.jpg', '//wx1.sinaimg.cn/square/6b002b97gy1ffs6ujijfoj206z05l746.jpg', '//wx1.sinaimg.cn/square/6b002b97gy1ffs6uimd6zj207705edfr.jpg' ); $email_hash = md5(strtolower(trim($email))); $random_avatar = array_rand($random_avatar_arr,1); $src = $random_avatar_arr[$random_avatar] ; // 参数404 onerror 方法 - 速度最快 $avatar = "<img alt='{$alt}' src='//secure.gravatar.com/avatar/{$email_hash}?d=404' onerror='javascript:this.src=\"{$src}\";this.onerror=null;' class='avatar avatar-{$size} photo' height='{$size}' width='{$size}' />"; // 参数default_img 方法 - 速度稍逊 // $src = urlencode( $src ); //$avatar = "<img alt='{$alt}' src='//secure.gravatar.com/avatar/{$email_hash}?d={$src}' class='avatar avatar-{$size} photo' height='{$size}' width='{$size}' />"; return $avatar; }

如果你想随机加载的头像更多,可以在代码中自行添加。

原文链接:https://www.qiquanji.com/post/8546.html

本站声明:网站内容来源于网络,如有侵权,请联系我们,我们将及时处理。

微信扫码关注

更新实时通知

« 上一篇 下一篇 »

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。