Comment obtenir l'URL de l'avatar au lieu d'une balise HTML IMG lorsque j'utilise get_avatar?
7 réponses
- votes
-
- 2015-05-13
Bonnenouvellepour les versions 4.2+ de WordPress
Depuis la version 4.2,lafonctionpratique
get_avatar_url()
,introduite sousforme de demande defonctionnalité dansticket # 21195 il y a quelques années,est désormais livré avec lenoyau :/** * Retrieve the avatar URL. * * @since 4.2.0 * * @param mixed $id_or_email The Gravatar to retrieve a URL for. Accepts a user_id, gravatar md5 hash, * user email, WP_User object, WP_Post object, or comment object. * @param array $args { * Optional. Arguments to return instead of the default arguments. * * @type int $size Height and width of the avatar in pixels. Default 96. * @type string $default URL for the default image or a default type. Accepts '404' (return * a 404 instead of a default image), 'retro' (8bit), 'monsterid' (monster), * 'wavatar' (cartoon face), 'indenticon' (the "quilt"), 'mystery', 'mm', * or 'mysterman' (The Oyster Man), 'blank' (transparent GIF), or * 'gravatar_default' (the Gravatar logo). Default is the value of the * 'avatar_default' option, with a fallback of 'mystery'. * @type bool $force_default Whether to always show the default image, never the Gravatar. Default false. * @type string $rating What rating to display avatars up to. Accepts 'G', 'PG', 'R', 'X', and are * judged in that order. Default is the value of the 'avatar_rating' option. * @type string $scheme URL scheme to use. See set_url_scheme() for accepted values. * Default null. * @type array $processed_args When the function returns, the value will be the processed/sanitized $args * plus a "found_avatar" guess. Pass as a reference. Default null. * } * @return false|string The URL of the avatar we found, or false if we couldn't find an avatar. */ function get_avatar_url( $id_or_email, $args = null ) { $args = get_avatar_data( $id_or_email, $args ); return $args['url']; }
où
get_avatar_data()
est également unenouvellefonction d'assistance.Il contient cettepartie de code:
... CUT ... /** * Filter whether to retrieve the avatar URL early. * * Passing a non-null value in the 'url' member of the return array will * effectively short circuit get_avatar_data(), passing the value through * the {@see 'get_avatar_data'} filter and returning early. * * @since 4.2.0 * * @param array $args Arguments passed to get_avatar_data(), after processing. * @param int|object|string $id_or_email A user ID, email address, or comment object. */ $args = apply_filters( 'pre_get_avatar_data', $args, $id_or_email ); if ( isset( $args['url'] ) && ! is_null( $args['url'] ) ) { /** This filter is documented in wp-includes/link-template.php */ return apply_filters( 'get_avatar_data', $args, $id_or_email ); } ... CUT ...
oùnouspouvons voir que lorsque leparamètre
url
est défini,lesfiltres disponibles sontpre_get_avatar_data
etget_avatar_data
.Après lamise àjour vers 4.2 récemment,j'aieu unproblème avec unthème qui définissait sapropre version de
get_avatar_url()
,sans aucun préfixe denom defonction ou unfunction_exists()
vérifier. Voici donc unexemple depourquoi c'estimportant ;-)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:/** * Retrieve the avatar URL. * * @since 4.2.0 * * @param mixed $id_or_email The Gravatar to retrieve a URL for. Accepts a user_id, gravatar md5 hash, * user email, WP_User object, WP_Post object, or comment object. * @param array $args { * Optional. Arguments to return instead of the default arguments. * * @type int $size Height and width of the avatar in pixels. Default 96. * @type string $default URL for the default image or a default type. Accepts '404' (return * a 404 instead of a default image), 'retro' (8bit), 'monsterid' (monster), * 'wavatar' (cartoon face), 'indenticon' (the "quilt"), 'mystery', 'mm', * or 'mysterman' (The Oyster Man), 'blank' (transparent GIF), or * 'gravatar_default' (the Gravatar logo). Default is the value of the * 'avatar_default' option, with a fallback of 'mystery'. * @type bool $force_default Whether to always show the default image, never the Gravatar. Default false. * @type string $rating What rating to display avatars up to. Accepts 'G', 'PG', 'R', 'X', and are * judged in that order. Default is the value of the 'avatar_rating' option. * @type string $scheme URL scheme to use. See set_url_scheme() for accepted values. * Default null. * @type array $processed_args When the function returns, the value will be the processed/sanitized $args * plus a "found_avatar" guess. Pass as a reference. Default null. * } * @return false|string The URL of the avatar we found, or false if we couldn't find an avatar. */ function get_avatar_url( $id_or_email, $args = null ) { $args = get_avatar_data( $id_or_email, $args ); return $args['url']; }
where
get_avatar_data()
is also a new helper function.It contains this code part:
... CUT ... /** * Filter whether to retrieve the avatar URL early. * * Passing a non-null value in the 'url' member of the return array will * effectively short circuit get_avatar_data(), passing the value through * the {@see 'get_avatar_data'} filter and returning early. * * @since 4.2.0 * * @param array $args Arguments passed to get_avatar_data(), after processing. * @param int|object|string $id_or_email A user ID, email address, or comment object. */ $args = apply_filters( 'pre_get_avatar_data', $args, $id_or_email ); if ( isset( $args['url'] ) && ! is_null( $args['url'] ) ) { /** This filter is documented in wp-includes/link-template.php */ return apply_filters( 'get_avatar_data', $args, $id_or_email ); } ... CUT ...
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 ;-) -
- 2012-07-25
La réponse ci-dessus semble complète,maisj'aijuste écrit unefonction wrapperet je suispassé à autre chose.Le voici si vousen avezbesoin (mettez ceci dans
functions.php
):function get_avatar_url($get_avatar){ preg_match("/src='(.*?)'/i", $get_avatar, $matches); return $matches[1]; }
puis utilisez-lepartout où vousen avezbesoin dans lesfichiersmodèles comme celui-ci:
<img src="<? echo get_avatar_url(get_avatar( $curauth->ID, 150 )); ?>" align="left" class="authorimage" />
C'estjusteplus simple.
L'utilisation de RegExpour analyser le HTML dans ce casest acceptable,car celane sera analysé qu'une seulebalise
img
,donc cene serapastrop coûteux.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
):function get_avatar_url($get_avatar){ preg_match("/src='(.*?)'/i", $get_avatar, $matches); return $matches[1]; }
and then use it wherver you need it in the template files like this:
<img src="<? echo get_avatar_url(get_avatar( $curauth->ID, 150 )); ?>" align="left" class="authorimage" />
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.-
Unpetit changement ... lafonctionget_avatarmet le src dans "non" donc la correspondance seranulle. Le regex devrait êtrepreg_match ('/src="(. *?)"/I',$get_avatar,$matches);A small change... the get_avatar function puts the src within " not ' so the match will be null. The regex should be preg_match('/src="(.*?)"/i', $get_avatar, $matches);
- 5
- 2014-09-17
- spdaly
-
merci @spdaly -j'espère que les commentairesinciteraient l'auteur à éditer;) -merci aalaapthanks @spdaly - i hope commenting would make the author to edit ;) - thanks aalaap
- 0
- 2014-12-21
- Sagive SEO
-
Si vous avez répondu à votrepropre question,veuillez lamarquer comme réponse acceptée.If you answered your own question please mark it as the accepted answer.
- 0
- 2016-08-01
- DᴀʀᴛʜVᴀᴅᴇʀ
-
@Darth_Vader Jen'y suispas retourné depuis quej'aiposté la question,doncje ne saisplus si c'est lamanièreidéale de lefaire.Jepense que lanouvelle réponse sur 4.2+estmeilleure.@Darth_Vader I haven't gone back to this since I posted the question, so I'm no longer sure if this is the ideal way to do it. I think the new answer about 4.2+ is better.
- 0
- 2016-08-02
- aalaap
-
- 2014-03-25
Jepense que c'est unemeilleure version de la réponse d'aalaap:
// In your template ... $avatar_url = get_avatar_url ( get_the_author_meta('ID'), $size = '50' ); // Get src URL from avatar <img> tag (add to functions.php) function get_avatar_url($author_id, $size){ $get_avatar = get_avatar( $author_id, $size ); preg_match("/src='(.*?)'/i", $get_avatar, $matches); return ( $matches[1] ); }
I think this a better version of aalaap's answer:
// In your template ... $avatar_url = get_avatar_url ( get_the_author_meta('ID'), $size = '50' ); // Get src URL from avatar <img> tag (add to functions.php) function get_avatar_url($author_id, $size){ $get_avatar = get_avatar( $author_id, $size ); preg_match("/src='(.*?)'/i", $get_avatar, $matches); return ( $matches[1] ); }
-
- 2015-04-15
get_user_meta($userId, 'simple_local_avatar');
Avatars locaux simples utilise des champsmétapour stocker l'avatar,vouspouvez donc simplementrécupérez la ou les valeursen appelant
get_user_meta
et en saisissant le "simple_local_avatar' champ.Vous obtiendrez untableau comme celui-ci:array ( [full] => 'http://...', [96] => 'http://...', [32] => 'http://...' )
get_user_meta($userId, 'simple_local_avatar');
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:array ( [full] => 'http://...', [96] => 'http://...', [32] => 'http://...' )
-
- 2015-04-25
Laméthode d'alaapne fonctionneplus sous Wordpress 4.2
J'aitrouvé une solution.Le voiciet çamarchebien:
function my_gravatar_url() { // Get user email $user_email = get_the_author_meta( 'user_email' ); // Convert email into md5 hash and set image size to 80 px $user_gravatar_url = 'http://www.gravatar.com/avatar/' . md5($user_email) . '?s=80'; echo $user_gravatar_url; }
dans Template,utilisez simplement:
<?php my_gravatar_url() ?>
Remarque:il doit être utilisé dans uneboucle.
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:
function my_gravatar_url() { // Get user email $user_email = get_the_author_meta( 'user_email' ); // Convert email into md5 hash and set image size to 80 px $user_gravatar_url = 'http://www.gravatar.com/avatar/' . md5($user_email) . '?s=80'; echo $user_gravatar_url; }
in Template just use:
<?php my_gravatar_url() ?>
Notice: it must be used inside a loop.
-
- 2014-11-27
Lorsque l'avatar a ététéléchargé localement,WP,renvoie labaliseimg avec l'attribut srcentreguillemets,j'ai donctrouvé que cemodèlefonctionnaitmieux:
preg_match("/src=['\"](.*?)['\"]/i", $get_avatar, $matches);
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:
preg_match("/src=['\"](.*?)['\"]/i", $get_avatar, $matches);
-
- 2014-12-14
Il y a quelques heures,je me demandais commentfaire ça aussi. Mais,bientôtj'aieu la solutionet créé unplugin,veuillez vérifier si get_avatar_url ($ user_id,$ size ) fonctionnepour vous oupas. Merci ..
Code duplugin:
/* Plugin Name: Get Avatar URL Plugin URI: https://github.com/faizan1041/get-avatar-url Description: get_avatar returns image, get_avatar_url will give you the image src. Author: Faizan Ali Version: 1.0 Author URI: https://github.com/faizan1041/ License: GPL v2+ */ function get_avatar_url($user_id, $size) { $avatar_url = get_avatar($user_id, $size); $doc = new DOMDocument(); $doc->loadHTML($avatar_url); $xpath = new DOMXPath($doc); $src = $xpath->evaluate("string(//img/@src)"); return $src; } function sc_get_avatar_url( $atts ) { $atts = shortcode_atts( array( 'email' => '', 'size' => 150 ), $atts, 'avatar_url' ); return get_avatar_url($atts['email'],$atts['size']); } add_shortcode( 'avatar_url', 'sc_get_avatar_url' );
Appel de lafonction:
get_avatar_url( get_the_author_meta( 'user_email'), 150);
Utilisation du shortcode:
do_shortcode('[avatar_url email="' . get_the_author_meta( 'user_email') .'" size=150 ]' );
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:
/* Plugin Name: Get Avatar URL Plugin URI: https://github.com/faizan1041/get-avatar-url Description: get_avatar returns image, get_avatar_url will give you the image src. Author: Faizan Ali Version: 1.0 Author URI: https://github.com/faizan1041/ License: GPL v2+ */ function get_avatar_url($user_id, $size) { $avatar_url = get_avatar($user_id, $size); $doc = new DOMDocument(); $doc->loadHTML($avatar_url); $xpath = new DOMXPath($doc); $src = $xpath->evaluate("string(//img/@src)"); return $src; } function sc_get_avatar_url( $atts ) { $atts = shortcode_atts( array( 'email' => '', 'size' => 150 ), $atts, 'avatar_url' ); return get_avatar_url($atts['email'],$atts['size']); } add_shortcode( 'avatar_url', 'sc_get_avatar_url' );
Usage:
Calling the function:
get_avatar_url( get_the_author_meta( 'user_email'), 150);
Using Shortcode:
do_shortcode('[avatar_url email="' . get_the_author_meta( 'user_email') .'" size=150 ]' );
J'utilise unplugin appelé Avatars locaux simples quime permet detélécharger desimages d'auteur qui sont stockéessurmon serveur localement (pas de Gravatar).Lepluginfonctionne correctementet
get_avatar
renvoie l'avatar local.Cependant,je dois utiliser cet avatar de différentesmanièreset à différentsendroitset pour cela,j'aibesoin de l'URL de l'image de l'avatar local au lieu de labalise HTMLentière.Jepourrais écrire unefonction wrapperpour
get_avatar
qui utilise RegEx ou SimpleXMLpour sélectionneret renvoyer uniquement l'URL,maisje me demandais s'ilexiste unmoyen de lefaire.