WordPress实现自动替换QQ头像

这篇文章讲述了如何在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 string|int|WP_User|WP_Comment|WP_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 = [
        "[email protected]"
    ];
    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

WordPress实现自动替换QQ头像 的发布基于协议 AHdark Blog License。如欲对此文章内容此文章转载、修改或行使任何超出预览和分享性质的行为,请参考此协议。

评论

  1. 小框
    Macintosh Opera
    1年前
    2022-4-06 19:58:07

    更正下 WordPress 的插件存储目录是 wp-content/plugins/,不是 wp-content/plugin/

  2. Android Chrome
    2年前
    2022-3-16 21:34:45

    大佬牛逼

  3. Leosion.
    Android Chrome
    2年前
    2021-10-05 17:20:56

    哎嘿还不错 :mrgreen:

发送评论 编辑评论


|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇