0

我想知道是否有办法在 wordpress 中获取当前登录用户头像的 URI/URL?我发现这是一种生成简码以使用 get_avatar 插入当前用户头像的方法(在 php 下方放置在主题 functions.php 中):

<?php

function logged_in_user_avatar_shortcode() {
if ( is_user_logged_in() ) {
global $current_user;
get_currentuserinfo();
return get_avatar( $current_user->ID );
}
}
add_shortcode('logged-in-user-avatar', 'logged_in_user_avatar_shortcode');

?>

但是,这会返回整个图像,包括属性(img src、class、width、height、alt)。我想只返回 URL,因为我已经在模板中为我的图像设置了所有属性。

试图做这样的事情:

<img src="[shortcode-for-avatar-url]" class="myclass" etc >

有谁知道这样做的方法?

提前谢谢了

4

2 回答 2

1

您可以使用preg_match以下网址查找网址:

function logged_in_user_avatar_shortcode()
{
    if ( is_user_logged_in() )
    {
        global $current_user;
        $avatar = get_avatar( $current_user->ID );
        preg_match("/src=(['\"])(.*?)\1/", $avatar, $match);
        return $match[2];
    }
}
add_shortcode('logged-in-user-avatar', 'logged_in_user_avatar_shortcode');
于 2014-01-23T14:37:59.197 回答
0

在最近的 WordPress 安装中,我编写了一个 PHP 函数来获取用户 gravatar,如果 WordPress 版本低于 2.5,我的函数使用了不同的方式来检索用户 gravatar。可以在下面找到仅输出用户 gravatar URI 的稍微修改的版本。

// Fallback for WP < 2.5
global $post;

$gravatar_post_id = get_queried_object_id();
$gravatar_author_id = get_post_field('post_author', $gravatar_post_id) || $post->post_author;//get_the_author_meta('ID');
$gravatar_email = get_the_author_meta('user_email', $gravatar_author_id);

$gravatar_hash = md5(strtolower(trim($gravatar_email)));
$gravatar_size = 68;
$gravatar_default = urlencode('mm');
$gravatar_rating = 'PG';
$gravatar_uri = 'http://www.gravatar.com/avatar/'.$gravatar_hash.'.jpg?s='.$gravatar_size.'&amp;d='.$gravatar_default.'&amp;r='.$gravatar_rating.'';

echo $gravatar_uri; // URI of GRAVATAR
于 2014-01-23T15:40:45.913 回答