Come ottengo l'URL dell'avatar invece di un tag HTML IMG quando utilizzo get_avatar?
7 risposta
- voti
-
- 2015-05-13
Buonenotizieper le versioni di WordPress 4.2+
Dalla versione 4.2 lapraticafunzione
get_avatar_url ()
,introdotta come richiesta difunzionalità nelticket # 21195 pochi annifa, ora vienefornito conil core :/** * Recupera l'URL dell'avatar. * * @since 4.2.0 * * @parammixed $id_or_email Il Gravatarper cui recuperare un URL. Accetta un hash user_id,gravatarmd5, *email utente,oggetto WP_User,oggetto WP_Post o oggetto commento. * @param array $ args { * Opzionale. Argomenti da restituireinvece degli argomentipredefiniti. * * @typeint $ size Altezzae larghezza dell'avatarin pixel. Predefinito 96. * @type string $ URLpredefinitoper l'immaginepredefinita o untipopredefinito. Accetta "404" (return * un 404invece di un'immaginepredefinita),"retro" (8bit),"monsterid" (mostro), * "wavatar" (faccia da cartone animato),"indenticon" (la "trapunta"),"mistero","mm", * o "mysteryman" (The Oyster Man),"blank" (GIFtrasparente) o * "gravatar_default" (il logo Gravatar). Il valorepredefinito èil valore di * Opzione "avatar_default",con riserva di "mistero". * @typebool $force_default Semostrare sempre l'immaginepredefinita,maiil Gravatar. Defaultfalse. * @type string $ rating Fino a qualepunteggio visualizzaregli avatar. Accetta "G","PG","R","X"e lo sono *giudicatoin quest'ordine. L'impostazionepredefinita èil valore dell'opzione "avatar_rating". * @type string $ schema URL schema da utilizzare. Vedere set_url_scheme ()peri valori accettati. * Defaultnull. * @type array $processing_args Quando lafunzione ritorna,il valore sarà $ argsprocessato/disinfettato *più un'ipotesi "found_avatar". Passa come riferimento. Nullpredefinito. *} * @returnfalse| string L'URL dell'avatar che abbiamotrovato ofalse senon siamo riusciti atrovare un avatar. */ funzioneget_avatar_url ($id_or_email,$ args=null) { $ args=get_avatar_data ($id_or_email,$ args); return $ args ['url']; } dove
get_avatar_data ()
è anche unanuovafunzione di supporto.Contiene questaparte di codice:
... CUT ... /** * Filtra se recuperarein anticipo l'URL dell'avatar. * * Ilpassaggio di un valorenonnullonelmembro 'url' dell'array di ritorno lofarà *effettivamente cortocircuitareget_avatar_data (),passandoil valore *ilfiltro {@see 'get_avatar_data'}e tornapresto. * * @since 4.2.0 * * @param array $ args Argomentipassati aget_avatar_data (),dopo l'elaborazione. * @paramint | object| string $id_or_email Un ID utente,unindirizzoemail o un oggetto commento. */ $ args=apply_filters ('pre_get_avatar_data',$ args,$id_or_email); if (isset ($ args ['url']) & amp; & amp;!is_null ($ args ['url'])) { /** Questofiltro è documentatoin wp-includes/link-template.php */ return apply_filters ('get_avatar_data',$ args,$id_or_email); } ... TAGLIO ... dovepossiamo vedere che quandoilparametro
url
èimpostato,i filtri disponibili sonopre_get_avatar_data
eget_avatar_data
.Dopo l'aggiornamento a 4.2 di recente,ho avuto unproblema con untema che definiva lapropria versione di
get_avatar_url ()
,senza alcun prefisso delnome dellafunzione ofunction_exists ()
check. Quindi questo è unesempio delperché èimportante ;-)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 risposta sopra sembra completa,ma ho appena scritto unafunzione wrappere sono andato avanti.Eccolo qui sene haibisogno (mettiloin
functions.php
):function get_avatar_url($get_avatar){ preg_match("/src='(.*?)'/i", $get_avatar, $matches); return $matches[1]; }
e poi usalo ovunqueti servanei filemodelloin questomodo:
<img src="<? echo get_avatar_url(get_avatar( $curauth->ID, 150 )); ?>" align="left" class="authorimage" />
È solopiù semplice.
L'uso di RegExper analizzare l'HTMLin questo caso vabene,perché questo analizzerà solo untag
img
,quindinon saràtroppo costoso.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.-
Unapiccolamodifica ... lafunzioneget_avatarinserisce src all'interno di "not",quindi la corrispondenza sarànulla. L'espressione regolare dovrebbeesserepreg_match ('/src="(. *?)"/I',$get_avatar,$match);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
-
grazie @spdaly - spero che commentandofaccia lamodifica all'autore;) -grazie aalaapthanks @spdaly - i hope commenting would make the author to edit ;) - thanks aalaap
- 0
- 2014-12-21
- Sagive SEO
-
Se hai risposto allatua domanda,contrassegnala come risposta accettata.If you answered your own question please mark it as the accepted answer.
- 0
- 2016-08-01
- DᴀʀᴛʜVᴀᴅᴇʀ
-
@Darth_Vader Non ci sonotornato da quando hopostato la domanda,quindinon sonopiù sicuro che questo siailmodoidealeperfarlo.Penso che lanuova risposta su 4.2+ siamigliore.@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
Penso che questa sia una versionemigliore della risposta di 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');
Simple Local Avatars utilizzai metacampipermemorizzare l'avatar,quindipuoi semplicementerecuperarei valori chiamando
get_user_meta
e afferrandoil 'simple_local_avatar' campo.Ti verrà restituito un arrayin questomodo: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
Ilmetodo di alaapnonfunzionapiùin Wordpress 4.2
Hotrovato una soluzione.Eccolo quie funzionabene:
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 usa semplicemente:
<?php my_gravatar_url() ?>
Avviso: deveessere utilizzato all'interno di un ciclo.
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
Quando l'avatar è stato caricato localmente,WP,restituisceiltagimg con l'attributo srctra virgolette,quindi hotrovato che questomodellofunzionavameglio:
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
Qualche orafa,mi chiedevo anche comefarlo. Mapresto ho ottenuto la soluzionee ho creato unplug-in,controlla se get_avatar_url ($ user_id,$ size ) funzionaperte ono. Grazie ..
Codiceplugin:
/* Nomeplugin: ottieni l'URL dell'avatar URI delplugin: https://github.com/faizan1041/get-avatar-url Descrizione:get_avatar restituisce l'immagine,get_avatar_urlti darà l'immagine src. Autore: Faizan Ali Versione: 1.0.0 URI dell'autore: https://github.com/faizan1041/ Licenza: GPL v2 + */ funzioneget_avatar_url ($ user_id,$ size) { $ avatar_url=get_avatar ($ user_id,$ size); $ doc=nuovo DOMDocument (); $ doc- > loadHTML ($ avatar_url); $ xpath=nuovo DOMXPath ($ doc); $ src=$ xpath- > assess ("string (//img/@ src)"); return $ src; } funzione sc_get_avatar_url ($ atts) { $ atts=shortcode_atts (array ( "email"=> '', 'size'=> 150 ),$ atts,'avatar_url'); returnget_avatar_url ($ atts ['email'],$ atts ['size']); } add_shortcode ('avatar_url','sc_get_avatar_url'); <"Usage:"
Chiamare lafunzione:
get_avatar_url (get_the_author_meta ('user_email'),150);
Utilizzo dello shortcode:
do_shortcode ('[avatar_urlemail="'.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 ]' );
Sto utilizzando unplugin chiamato Simple Local Avatars chemi permette di caricareimmagini dell'autore che vengonomemorizzatesulmio serverin locale (no Gravatar).Ilpluginfunzionabene e
get_avatar
restituisce l'avatar locale.Tuttavia,hobisogno di usare quell'avatarin modie luoghi diversie per questo hobisogno dell'URL dell'immagine dell'avatar localeinvece dell'interotag HTML.Potrei scrivere unafunzione wrapperper
get_avatar
che utilizza RegEx o SimpleXMLper selezionaree restituire solo l'URL,mami chiedevo seesiste unmodoesistenteperfarlo.