問題描述

我用一個 WP 黑客來顯示作者的照片。例如,我的 s​​ingle.php 有一個作者 slug 顯示作者的圖片。

我在我的主題/圖像文件夾中創建了一個名為 authors 的文件夾。根據作者的 ID,我命名為 1.jpg,2.jpg 等等。

所以我稱這個圖像為

<img src="<?php%20bloginfo('template_directory')%20?>/images/authors/<?php%20the_author_ID()?>.jpg" alt="<?php the_author(); ?>">

現在我正在修改一個在側邊欄中顯示作者的插件。但是這個插件使用了 get_avatar 功能,如下所示:

/**
                 * If show avatar option is checked, add get_avatar function to cache.
                 */
                if($jmetc_options['show_avatar'] == 1) {
                    $jmevar['cache'] .= get_avatar($tc->comment_author_email, $jmetc_options['avatar_size']);
                }

有人建議我如何使用/修改 get_avatar 以使用我使用的默認代碼?

最佳解決方案

get_avatar()功能適用於 get_avatar 過濾器掛鈎,可用於更改頭像標記:

return apply_filters('get_avatar', $avatar, $id_or_email, $size, $default, $alt);

我認為這是掛鈎這個過濾器的正確方法:

function mytheme_get_avatar( $avatar ) {
    $avatar = '<img src="<'%20.%20get_template_directory_uri()%20.%20'/images/authors/'%20.%20get_the_author_ID()%20.%20'.jpg" alt="' . get_the_author() . '">';
    return $avatar;
}
add_filter( 'get_avatar', 'mytheme_get_avatar' );

編輯

附:這種方法的一個不錯的選擇可能是 Simple Local Avatars 插件。

編輯 2

使用 add_filter()而不是 apply_filters()應用過濾器。那是我的錯字現在固定!

編輯 3

我不認為這是正確的:

P.S: Just to clarify.. I replaced get_avatar($tc->comment_author_email, $jmetc_options['avatar_size']); with add_filter('get_avatar', $avatar, $id_or_email, $size, $default, $alt);

首先,您仍然在模板文件中調用 get_avatar(),傳遞與上一個相同的參數。 add_filter()呼叫屬於 functions.php

其次,您可以將其他參數傳遞給過濾器功能; 例如。:

function mytheme_get_avatar( $avatar, $id_or_email, $size ) {
    $avatar = '<img src="<'%20.%20get_template_directory_uri()%20.%20'/images/authors/'%20.%20$id_or_email%20.%20'.jpg" alt="' . get_the_author() . '" width="' . $size . 'px" height="' . $size . 'px" />';
    return $avatar;
}
add_filter( 'get_avatar', 'mytheme_get_avatar', 10, 3 );

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。