使用 LetterAvatar 脚本生成首字图片替代默认评论头像

WP教程评论4411字数 4079阅读模式

Gravatar 是全球通用头像,如果我们没有设置 Gravatar 头像,那么在网站上留言或评论就会显示默认的头像或者随机头像,这样的话用户体验不是很好。今天为大家分享一下使用 LetterAvatar 脚本自动生成首字图片代替默认头像的方法。

使用 LetterAvatar 脚本生成首字图片替代默认评论头像

使用方法

LetterAvatar 脚本是通过读取 ALT 属性来自动生成图片的,所以基本思想是:首先给图片添加 ALT 属性,然后判断有无 Gravatar 头像,有的话显示 Gravatar 头像,没有的话显示 LetterAvatar 脚本生成的首字图片头像(比如昵称的第一个字符)。

1、头像添加ALT属性

查看WP官网 get_avatar 默认的可选参数:

<?php echo get_avatar( $id_or_email, $size, $default, $alt, $args ); ?>

其中:$alt 就是 alt 可选参数。

打开主题评论模板,找到类似这句:

<?php echo get_avatar( $comment, 64 ); ?>

替换为:

<?php echo get_avatar( $comment, 64, '', get_comment_author() ); ?>

将评论者名称作为 ALT 属性。

2、判断有无头像

如果没有使用 Gravatar,则给头像 img 标签添加一个 class 属性,比如 letter,示例代码(部分)如下:

      
if (!preg_match("|200|", $headers[0])) {
    // 没有头像,则新建一个空白文件作为标记
    $handle = fopen($d, 'w');
    fclose($handle);
    $a = $default;
    $letter = 'letter'; //无头像添加一个class属性:letter
} else {
    // 有头像且不存在则更新
    $r = get_option('avatar_rating');
    $g = 'http://www.gravatar.com/avatar/'.$f.'?s='.$size.'&r='.$r;
    copy($g, $e);
    $letter = '';
}
//在img标签中添加class属性letter
$avatar = "<img class='avatar avatar-{$size} photo {$letter}' alt='{$alt}' src='{$a}' height='{$size}' width='{$size}' />";
因为大部分网站使用了缓存,所以需要同时修改缓存文件中的代码。

3、渲染首字头像

通过 LetterAvatar 脚本渲染首字头像,LetterAvatar 是一个开原项目,将示例中的 JS 脚本添加到你的网站。

示例代码:

展开收缩
<!DOCTYPE html>
<html>
<h1>Letter Avatar</h1>
<small><strong>Usage:</strong></small>
<pre>
    <code><img width="256" height="256" avatar="Dao Lam" color="#0D8ABC"></code>
</pre>
<div>
    <img width="256" height="256" avatar="Dao Lam" color="#0D8ABC">
    <img class="round" width="256" height="256" avatar="Dao Lam" color="#0D8ABC">
</div>
<div>
    <img width="256" height="256" avatar="decentralized Market" color="#0D8ABC">
    <img class="round" width="256" height="256" avatar="decentralized Market" color="#0D8ABC">
</div>
<style>
    body {
      font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
    }
    pre {
      margin: 20px 0;
      padding: 20px;
      background: #fafafa;
    }
    .round { border-radius: 50%; }
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
    /*
     * LetterAvatar
     * 
     * Artur Heinze
     * Create Letter avatar based on Initials
     * based on https://gist.github.com/leecrossley/6027780
     */
    (function(w, d){
        function LetterAvatar (name, size, color) {
            name  = name || '';
            size  = size || 60;
            var colours = [
                    "#1abc9c", "#2ecc71", "#3498db", "#9b59b6", "#34495e", "#16a085", "#27ae60", "#2980b9", "#8e44ad", "#2c3e50", 
                    "#f1c40f", "#e67e22", "#e74c3c", "#ecf0f1", "#95a5a6", "#f39c12", "#d35400", "#c0392b", "#bdc3c7", "#7f8c8d"
                ],
                nameSplit = String(name).split(' '),
                initials, charIndex, colourIndex, canvas, context, dataURI;
            if (nameSplit.length == 1) {
                initials = nameSplit[0] ? nameSplit[0].charAt(0):'?';
            } else {
                initials = nameSplit[0].charAt(0) + nameSplit[1].charAt(0);
            }
            if (w.devicePixelRatio) {
                size = (size * w.devicePixelRatio);
            }
            charIndex     = (initials == '?' ? 72 : initials.charCodeAt(0)) - 64;
            colourIndex   = charIndex % 20;
            canvas        = d.createElement('canvas');
            canvas.width  = size;
            canvas.height = size;
            context       = canvas.getContext("2d");
            context.fillStyle = color ? color : colours[colourIndex - 1];
            context.fillRect (0, 0, canvas.width, canvas.height);
            context.font = Math.round(canvas.width/2)+"px Arial";
            context.textAlign = "center";
            context.fillStyle = "#FFF";
            context.fillText(initials, size / 2, size / 1.5);
            dataURI = canvas.toDataURL();
            canvas  = null;
            return dataURI;
        }
        LetterAvatar.transform = function() {
            Array.prototype.forEach.call(d.querySelectorAll('img[avatar]'), function(img, name, color) {
                name = img.getAttribute('avatar');
                color = img.getAttribute('color');
                img.src = LetterAvatar(name, img.getAttribute('width'), color);
                img.removeAttribute('avatar');
                img.setAttribute('alt', name);
            });
        };
        // AMD support
        if (typeof define === 'function' && define.amd) {
            define(function () { return LetterAvatar; });
        // CommonJS and Node.js module support.
        } else if (typeof exports !== 'undefined') {
            // Support Node.js specific `module.exports` (which can be a function)
            if (typeof module != 'undefined' && module.exports) {
                exports = module.exports = LetterAvatar;
            }
            // But always support CommonJS module 1.1.1 spec (`exports` cannot be a function)
            exports.LetterAvatar = LetterAvatar;
        } else {
            window.LetterAvatar = LetterAvatar;
            d.addEventListener('DOMContentLoaded', function(event) {
                LetterAvatar.transform();
            });
        }
    })(window, document);
</script>
</html>

其中,需要修改一个地方,将:

querySelectorAll('img[avatar]')

修改为:

querySelectorAll('.letter[alt]')

即根据 img 标签查找改为根据 class 查找。

结束语

如果你的网站还在使用默认头像的话,不妨尝试一下这个方法。本文是以 wordpress 为例来说明的,如果网站是用其他程序搭建的,大家可以自行修改一下代码,其实现原理是一样的。如果有任何意见或建议,欢迎在下方评论处留言。

本文已通过「原本」原创作品认证,转载请注明文章出处及链接。

夏日阳光
  • 本文由 夏日阳光 发表于 2021年8月13日
  • 本文为夏日阳光原创文章,转载请务必保留本文链接:https://www.pieruo.com/186.html
匿名

发表评论

匿名网友
:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:
确定

拖动滑块以完成验证