WordPress 实现自动替换 QQ 头像

· Technology

这篇文章讲述了如何在WordPress使用QQ头像

代码

将以下代码复制到 /wp-content/plugin/qq-avatar.php 即可

<?php
/**
 * Plugin Name: QQ Avatar
 * Description: Retrieve the avatar when it is generated, if it is a QQ mail address, return the QQ avatar.
 * Version: 1.0.0
 * Author: AHdark
 * Author URI: https://www.ahdark.blog
 */

/**
 * Set avatar from QQ if the rule accepted
 * @param string $avatar
 * @param stringintWP_UserWP_CommentWP_Post $id_or_email
 * @param int $size
 * @param string $default
 * @param string $alt
 * @return string
 */
function setQQAvatar(string $avatar, $id_or_email, int $size, string $default, string $alt): string
{
    $email = null;

    /* Get Email from $id_or_email */
    if (is_email($id_or_email)) {
        $email = $id_or_email->comment_author_email;
    } else if (!empty($id_or_email->comment_author_email)) {
        $email = $id_or_email->comment_author_email;
    } else if (!empty($id_or_email->post_author)) {
        $email = get_userdata($id_or_email->post_author)->user_email;
    } else if (!empty($id_or_email->user_email)) {
        $email = $id_or_email->user_email;
    }

    /* White List */
    $white_list = [
        "2533313894@qq.com"
    ];
    if (in_array($email, $white_list)) {
        return $avatar;
    }

    /* Replace Html Element */
    $email = explode("@", $email);
    if ($email[1] === "qq.com" && preg_match("/^[1-9][0-9]{4,9}/i", $email[0])) {
        if ($size <= 40) {
            $src = "https://q.qlogo.cn/headimg_dl?dst_uin=$email[0]&spec=2&img_type=jpg";
        } else if ($size <= 140) {
            $src = "https://q.qlogo.cn/headimg_dl?dst_uin=$email[0]&spec=4&img_type=jpg";
        } else {
            $src = "https://q.qlogo.cn/headimg_dl?dst_uin=$email[0]&spec=5&img_type=jpg";
        }
        return "<img alt='$alt' src='$src' class='avatar avatar-$size photo' height='$size' width='$size' loading='lazy' />";
    }

    return $avatar;
}

add_filter("get_avatar", "setQQAvatar", 10, 5);

问题

你可能也看出来了,这个会替换所有使用qq.com后缀的邮箱的头像

为此我的方法是通过Gravatar API进行判断,但这严重影响了站点的加载速度

所以,先用White List凑活吧……

我还在想更好的解决方案,实在不行就前端替换大法了,反正有comment-id

Comments

Send Comments

Markdown supported. Please keep comments clean.