i want to get the user avatar URL to use it as background URL style for a div. i tried to use the following but it does not return anything when i view the code it appears like that.

background: url()

i used this function.

function get_avatar_url($get_avatar){
preg_match("/src='(.*?)'/i", $get_avatar, $matches);
return $matches[1];

any help please??

  • 2
    Where is the $get_avatar variable coming from? Commented Aug 27, 2012 at 12:42

3 Answers 3


It's fairly simple to construct the Gravatar URL yourself, it's just an MD5 hash of the user's email address.

<?php $gravatar = 'http://www.gravatar.com/avatar/' . md5(strtolower($email)) . '&s=32'; ?>

<div class="avatar" style="background: url(<?php echo $gravatar ?>);" ></div>

The s parameter at the end there defines the size of the image in pixels.

Using Gravatars - WordPress Codex


function get_avatar_url( $avatar, $id_or_email, $size = 96, $default = '', $alt = '' ) {

    preg_match( '#src=["|\'](.+)["|\']#Uuis', $avatar, $matches );

    return ( isset( $matches[1] ) && ! empty( $matches[1]) ) ?
        (string) $matches[1] : '';  


Apply a filter on get_avatar, it takes 5 arguments (!). The first one is the complete <img>-tag. And do not forget the source can be enclosed with double and single quotes ( ["|'] ). I guess that was the point where your function failed.


As of WordPress version 4.2.0, we can use get_avatar_url(). The function can be found in wp-includes/link-template.php:

function get_avatar_url( $id_or_email, $args = null ) {
    $args = get_avatar_data( $id_or_email, $args );
    return $args['url'];

So you can simply use it by:

$avatar_url = get_avatar_url($user_id);

Also, I know this is an old question, but a great lesson to be learned. Always use prefixes when you add your custom functions. Your custom function is get_avatar_url() and so is the newly added core function get_avatar_url(). You would have received an error when you upgraded to 4.2.0.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.