search
HomeCMS TutorialWordPressWordPress script to replace images with letters: LetterAvatar

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');

之后,自动将评论者昵称做为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 class="avatar photo lazy"  src="/static/imghwm/default1.png"  data-src="" class="       style="max-width:90%"  style="max-width:90%" alt="知更鸟" color="#c40000"></code>
  WordPress script to replace images with letters: LetterAvatar WordPress script to replace images with letters: LetterAvatar WordPress script to replace images with letters: LetterAvatar   <script></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 || &#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>

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
This article is reproduced at:zmingcx. If there is any infringement, please contact admin@php.cn delete
Can I learn WordPress in 3 days?Can I learn WordPress in 3 days?Apr 09, 2025 am 12:16 AM

Can learn WordPress within three days. 1. Master basic knowledge, such as themes, plug-ins, etc. 2. Understand the core functions, including installation and working principles. 3. Learn basic and advanced usage through examples. 4. Understand debugging techniques and performance optimization suggestions.

Is WordPress a CMS?Is WordPress a CMS?Apr 08, 2025 am 12:02 AM

WordPress is a Content Management System (CMS). It provides content management, user management, themes and plug-in capabilities to support the creation and management of website content. Its working principle includes database management, template systems and plug-in architecture, suitable for a variety of needs from blogs to corporate websites.

What is the WordPress good for?What is the WordPress good for?Apr 07, 2025 am 12:06 AM

WordPressisgoodforvirtuallyanywebprojectduetoitsversatilityasaCMS.Itexcelsin:1)user-friendliness,allowingeasywebsitesetup;2)flexibilityandcustomizationwithnumerousthemesandplugins;3)SEOoptimization;and4)strongcommunitysupport,thoughusersmustmanageper

Should I use Wix or WordPress?Should I use Wix or WordPress?Apr 06, 2025 am 12:11 AM

Wix is ​​suitable for users who have no programming experience, and WordPress is suitable for users who want more control and expansion capabilities. 1) Wix provides drag-and-drop editors and rich templates, making it easy to quickly build a website. 2) As an open source CMS, WordPress has a huge community and plug-in ecosystem, supporting in-depth customization and expansion.

How much does WordPress cost?How much does WordPress cost?Apr 05, 2025 am 12:13 AM

WordPress itself is free, but it costs extra to use: 1. WordPress.com offers a package ranging from free to paid, with prices ranging from a few dollars per month to dozens of dollars; 2. WordPress.org requires purchasing a domain name (10-20 US dollars per year) and hosting services (5-50 US dollars per month); 3. Most plug-ins and themes are free, and the paid price ranges from tens to hundreds of dollars; by choosing the right hosting service, using plug-ins and themes reasonably, and regularly maintaining and optimizing, the cost of WordPress can be effectively controlled and optimized.

Is WordPress still free?Is WordPress still free?Apr 04, 2025 am 12:06 AM

The core version of WordPress is free, but other fees may be incurred during use. 1. Domain names and hosting services require payment. 2. Advanced themes and plug-ins may be charged. 3. Professional services and advanced features may be charged.

Is WordPress easy for beginners?Is WordPress easy for beginners?Apr 03, 2025 am 12:02 AM

WordPress is easy for beginners to get started. 1. After logging into the background, the user interface is intuitive and the simple dashboard provides all the necessary function links. 2. Basic operations include creating and editing content. The WYSIWYG editor simplifies content creation. 3. Beginners can expand website functions through plug-ins and themes, and the learning curve exists but can be mastered through practice.

Why would anyone use WordPress?Why would anyone use WordPress?Apr 02, 2025 pm 02:57 PM

People choose to use WordPress because of its power and flexibility. 1) WordPress is an open source CMS with strong ease of use and scalability, suitable for various website needs. 2) It has rich themes and plugins, a huge ecosystem and strong community support. 3) The working principle of WordPress is based on themes, plug-ins and core functions, and uses PHP and MySQL to process data, and supports performance optimization.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)