Wordpress codex: php for URL of current user avatar

4.4k Views Asked by At

I was wondering if there is a way to get the URI/URL of the current logged-in user's avatar in wordpress? I found this as a way to generate a shortcode to insert the current user avatar using get_avatar (below php to be placed in theme 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');

?>

However, this returns the whole image including attributes (img src, class, width, height, alt). I want to return just the URL alone because i have already set all the attributes for my image in the template.

Trying to make something like this:

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

Does anyone know a way to do this?

Many thanks in advance

3

There are 3 best solutions below

0
On

I know this is a old question, but for anyone looking, there's a more concise way to get the avatar url with get_avatar_url(). (More info here.)

global $current_user; wp_get_current_user();
$avatar_url = get_avatar_url( $current_user->ID );
3
On

You can use preg_match to find the 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');
1
On

I wrote a PHP function to get a users gravatar in recent WordPress installations, if WordPress is less than version 2.5 my function used a different way of retrieving a users gravatar. A slightly modified version that simply outputs a users gravatar URI can be found below.

// 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