在WordPress中使用get_avatar顯示使用者頭像

在WordPress中使用get_avatar顯示使用者頭像

頭像是 WordPress 的重要組成部分,無論您是在開發主題還是在開發自定義功能,我們都將在本篇文章中介紹在 WordPress 中獲取使用者頭像的所有方法。

通常情況下,WordPress 中的頭像會顯示 Gravatar,但下面的所有功能都可以通過外掛在 WordPress 中替代 Gravatar 的功能。

如何顯示當前登入使用者的頭像

在 WordPress 中,使用 get_avatar() 可以輕鬆獲取當前登入使用者的頭像。通過該函式,您可以輸入使用者 ID、頭像大小,並輸出帶有正確頭像的圖片標籤。

我還提供了一個使用 get_avatar_url() 的程式碼片段,它可以讓你直接獲取使用者頭像的 URL,並以任何你想要的方式使用。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
// Ensure user is logged in
if( is_user_logged_in() ) {
// Display current logged in user's avatar (includes <img> tag)
echo get_avatar( get_current_user_id(), 96 );
// Display current logged in user's avatar URL
echo get_avatar_url( get_current_user_id(), array( 'size' => 96 ) );
}
<?php // Ensure user is logged in if( is_user_logged_in() ) { // Display current logged in user's avatar (includes <img> tag) echo get_avatar( get_current_user_id(), 96 ); // Display current logged in user's avatar URL echo get_avatar_url( get_current_user_id(), array( 'size' => 96 ) ); }
<?php
// Ensure user is logged in
if( is_user_logged_in() ) {
 // Display current logged in user's avatar (includes <img> tag)
 echo get_avatar( get_current_user_id(), 96 );

 // Display current logged in user's avatar URL
 echo get_avatar_url( get_current_user_id(), array( 'size' => 96 ) );
}

您可以將上述程式碼片段用於 WordPress 網站上的任何自定義功能。例如,在自定義主題中將登入使用者的頭像新增到頁首。

在上面的示例函式中,我還指定頭像的大小為 96。你可以將 “96” 替換為你想要的頭像的高度/寬度。如果解析度較高,可以使用 512,如果解析度較低,可以使用 32。

如何顯示當前文章作者的頭像

使用上述 get_avatarget_avatar_url 函式,您還可以輕鬆獲取任何使用者 ID 的頭像。這樣就能輕鬆顯示當前文章的作者頭像。

使用 get_the_author_meta() 函式,我們可以獲取當前文章的作者 ID,並將其用於顯示當前文章作者頭像的函式中。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
// Display current post's author avatar (includes <img> tag)
echo get_avatar( get_the_author_meta( 'ID' ), 96 );
// Display current post's author avatar URL
echo get_avatar_url( get_the_author_meta( 'ID' ), array( 'size' => 96 ) );
<?php // Display current post's author avatar (includes <img> tag) echo get_avatar( get_the_author_meta( 'ID' ), 96 ); // Display current post's author avatar URL echo get_avatar_url( get_the_author_meta( 'ID' ), array( 'size' => 96 ) );
<?php
// Display current post's author avatar (includes <img> tag)
echo get_avatar( get_the_author_meta( 'ID' ), 96 );

// Display current post's author avatar URL
echo get_avatar_url( get_the_author_meta( 'ID' ), array( 'size' => 96 ) );

當然,您必須在迴圈中使用這段程式碼。大多數情況下,在主題或函式中使用它都能正常工作。

希望這篇文章對你理解如何在 WordPress 開發中使用 get_avatar 有所幫助。如果你有任何關於 WordPress 開發或 WordPress 程式碼片段的問題,請在下面的評論中告訴我。

評論留言