Table of Contents
Letter Avatar
Home CMS Tutorial WordPress WordPress script to replace images with letters: LetterAvatar

WordPress script to replace images with letters: LetterAvatar

Apr 21, 2020 pm 01:55 PM
wordpress

WordPress script to replace images with letters: LetterAvatar

下面由WordPress技巧栏目给大家介绍关于用字母替代图片脚本:LetterAvatar,希望对需要的朋友有所帮助!

基于canvas,通过toDataURL动态生成base64图片。目前我主题的Gravatar头像,就是利用这个LetterAvatar脚本实现未设置Gravatar头像则读取ALT标签,自动生成首字图片替代默认的头像图片。

WordPress script to replace images with letters: LetterAvatar

之前已有WP爱好者制作了一款:mk-letter-avatar 字母头像插件,试了一下很好用,不过打开浏览器开者工具发现产生大量404错误,看了一下源代码,该插件是通过无头像返回404错误,触发onerror事件用自动生成的字母图片替换src图片地址,判断方式不是很合理,如果不是因为个缺点我都想直接拿来用了,如果作者再优化一下,绝对是款优秀实用的插件。

我的实现原理和插件不同,配合头像本地缓存功能,判断无头像后,直接为无头像的图片添加特定的class类,然后通过LetterAvatar脚本替换图片。

需要注意的是上面提到的插件,Gravatar头像图片必须有alt标签属性,否则不会生成正常的图片,可惜大部分主题默认Gravatar头像alt标签属性是空的.....

如果想自动为Gravatar头像添加alt标签属性,可以将下面的代码添加到当前主题函数模板functions.php中:

function zm_gravatar_alt($altgravatar) {
if (have_comments()) {
$alt = get_comment_author();
}
else {
$alt = get_the_author_meta('display_name');
}
$altgravatar= str_replace('alt=\'\'', 'alt=\'' . $alt . '\' title=\'Gravatar for ' . $alt . '\'', $altgravatar);
return $altgravatar;
}
add_filter('get_avatar', 'zm_gravatar_alt');
Copy after login

之后,自动将评论者昵称做为alt属性。

本文只是自己做个记录,并不是教大家怎么弄这个头像,如果认为这字母头像还不错,请直接使用上面介绍的插件。

另附LetterAvatar脚本演示代码:

<!DOCTYPE html>
<html>
<h1 id="Letter-nbsp-Avatar">Letter Avatar</h1>
 
<small><strong>用法:</strong></small>
<pre class="brush:php;toolbar:false">
<code><img src="" class="avatar photo" width="256" height="256" alt="知更鸟" color="#c40000"></code>
Copy after login
知更鸟 更鸟 鸟 <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 || &#39;&#39;; 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(&#39; &#39;), initials, charIndex, colourIndex, canvas, context, dataURI; if (nameSplit.length == 1) { initials = nameSplit[0] ? nameSplit[0].charAt(0):&#39;?&#39;; } else { initials = nameSplit[0].charAt(0) + nameSplit[1].charAt(0); } if (w.devicePixelRatio) { size = (size * w.devicePixelRatio); } charIndex = (initials == &#39;?&#39; ? 72 : initials.charCodeAt(0)) - 64; colourIndex = charIndex % 20; canvas = d.createElement(&#39;canvas&#39;); 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(&#39;img[alt]&#39;), function(img, name, color) { name = img.getAttribute(&#39;alt&#39;); color = img.getAttribute(&#39;color&#39;); img.src = LetterAvatar(name, img.getAttribute(&#39;width&#39;), color); img.removeAttribute(&#39;avatar&#39;); img.setAttribute(&#39;alt&#39;, name); }); }; // AMD support if (typeof define === &#39;function&#39; && define.amd) { define(function () { return LetterAvatar; }); // CommonJS and Node.js module support. } else if (typeof exports !== &#39;undefined&#39;) { // Support Node.js specific `module.exports` (which can be a function) if (typeof module != &#39;undefined&#39; && 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(&#39;DOMContentLoaded&#39;, function(event) { LetterAvatar.transform(); }); } })(window, document); </script>

原项目地址:https://github.com/daolavi/LetterAvatar

推荐教程:《WordPress

The above is the detailed content of WordPress script to replace images with letters: LetterAvatar. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to adjust the wordpress article list How to adjust the wordpress article list Apr 20, 2025 am 10:48 AM

There are four ways to adjust the WordPress article list: use theme options, use plugins (such as Post Types Order, WP Post List, Boxy Stuff), use code (add settings in the functions.php file), or modify the WordPress database directly.

What are the plugins for wordpress blocking ip What are the plugins for wordpress blocking ip Apr 20, 2025 am 08:27 AM

WordPress IP blocking plugin selection is crucial. The following types can be considered: based on .htaccess: efficient, but complex operation; database operation: flexible, but low efficiency; firewall: high security performance, but complex configuration; self-written: highest control, but requires more technical level.

How to cancel the editing date of wordpress How to cancel the editing date of wordpress Apr 20, 2025 am 10:54 AM

WordPress editing dates can be canceled in three ways: 1. Install the Enable Post Date Disable plug-in; 2. Add code in the functions.php file; 3. Manually edit the post_modified column in the wp_posts table.

How to write a header of a wordpress How to write a header of a wordpress Apr 20, 2025 pm 12:09 PM

The steps to create a custom header in WordPress are as follows: Edit the theme file "header.php". Add your website name and description. Create a navigation menu. Add a search bar. Save changes and view your custom header.

How to change the head image of the wordpress theme How to change the head image of the wordpress theme Apr 20, 2025 am 10:00 AM

A step-by-step guide to replacing a header image of WordPress: Log in to the WordPress dashboard and navigate to Appearance &gt;Theme. Select the topic you want to edit and click Customize. Open the Theme Options panel and look for the Site Header or Header Image options. Click the Select Image button and upload a new head image. Crop the image and click Save and Crop. Click the Save and Publish button to update the changes.

How to build a website for wordpress host How to build a website for wordpress host Apr 20, 2025 am 11:12 AM

To build a website using WordPress hosting, you need to: select a reliable hosting provider. Buy a domain name. Set up a WordPress hosting account. Select a topic. Add pages and articles. Install the plug-in. Customize your website. Publish your website.

What to do if there is an error in wordpress What to do if there is an error in wordpress Apr 20, 2025 am 11:57 AM

WordPress Error Resolution Guide: 500 Internal Server Error: Disable the plug-in or check the server error log. 404 Page not found: Check permalink and make sure the page link is correct. White Screen of Death: Increase the server PHP memory limit. Database connection error: Check the database server status and WordPress configuration. Other tips: enable debug mode, check error logs, and seek support. Prevent errors: regularly update WordPress, install only necessary plugins, regularly back up your website, and optimize website performance.

How to display wordpress comments How to display wordpress comments Apr 20, 2025 pm 12:06 PM

Enable comments in WordPress website: 1. Log in to the admin panel, go to "Settings" - "Discussions", and check "Allow comments"; 2. Select a location to display comments; 3. Customize comments; 4. Manage comments, approve, reject or delete; 5. Use &lt;?php comments_template(); ?&gt; tags to display comments; 6. Enable nested comments; 7. Adjust comment shape; 8. Use plugins and verification codes to prevent spam comments; 9. Encourage users to use Gravatar avatar; 10. Create comments to refer to

See all articles