Wordpress codex:当前用户头像 URL 的 php

问题描述 投票:0回答:3

我想知道是否有办法在wordpress中获取当前登录用户头像的URI/URL?我发现这是一种生成短代码以使用 get_avatar 插入当前用户头像的方法(位于主题functions.php中的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 >

有人知道如何做到这一点吗?

提前非常感谢

php wordpress shortcode avatar codex
3个回答
1
投票

您可以使用

preg_match
来查找URL:

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');

0
投票

我编写了一个 PHP 函数来在最近安装的 WordPress 中获取用户头像,如果 WordPress 版本低于 2.5,我的函数会使用不同的方式来检索用户头像。下面是一个稍微修改过的版本,它只输出用户头像 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

0
投票

我知道这是一个老问题,但对于任何寻找的人来说,有一种更简洁的方法可以使用

get_avatar_url()
获取头像网址。 (更多信息请点击这里。

global $current_user; wp_get_current_user();
$avatar_url = get_avatar_url( $current_user->ID );
© www.soinside.com 2019 - 2024. All rights reserved.