I’m using a plugin called Simple Local Avatars which lets me upload author images which are stored on my server locally (no Gravatar). The plugin works fine and get_avatar
returns the local avatar.
However, I need to use that avatar in different ways and different places and for that I need the local avatar image URL instead of the entire HTML tag. I could write a wrapper function for get_avatar
that uses RegEx or SimpleXML to pick out and return only the URL, but I was wondering if there’s any existing way to do this.
Good news for WordPress versions 4.2+
Since version 4.2 the handy
get_avatar_url()
function, introduced as a feature request in ticket #21195 few years ago, now ships with the core:where
get_avatar_data()
is also a new helper function.It contains this code part:
where we can see that when the
url
parameter is set, the available filters arepre_get_avatar_data
andget_avatar_data
.After upgrading to 4.2 recently, I had a problem with a theme that defined it’s own version of
get_avatar_url()
, without any function name prefixing or afunction_exists()
check. So this is an example of why that’s important 😉The answer above seems comprehensive, but I just wrote a wrapper function and moved on. Here it is if you need it (put this in
functions.php
):and then use it wherver you need it in the template files like this:
It’s just simpler.
Using RegEx to parse HTML in this case is okay, because this will only be parsing one
img
tag, so it won’t be too costly.You can use the filter
get_avatar
for get all data to the avatar, also the url inside the markup. I think, WP don`t have an function for return only the url if the avatar image.Also you can rewrite this function inside an plugin or theme, the function is onyl active, if this function name is not on other place defined.
So it is possible to add an param for return only the url of the image, like this, use the param
$url
withTRUE
and you get only the url.Another small variant is, that you create the url with the rule of Gravatar.
use this on your source with the emails of authors and you get the url of there image.
I think this a better version of aalaap’s answer:
Simple Local Avatars uses meta fields to store the avatar, so you can simply retrieve the value(s) by calling
get_user_meta
and grabbing the ‘simple_local_avatar’ field. You’ll get returned an array like so:alaap’s method doesn’t work anymore in WordPress 4.2
I came up with a solution. Here it is and it’s working good:
in Template just use:
Notice: it must be used inside a loop.
When the avatar has been uploaded locally, WP, returns the img tag with the src attribute in double quotes, so I found this pattern worked better:
A few hours ago, I was wondering how to do that too. But, soon I got the solution and made a plugin, please check whether get_avatar_url($user_id, $size)
works for you or not. Thanks..
Plugin code:
Usage:
Calling the function:
Using Shortcode: