Come ottengo lURL dellavatar invece di un tag HTML IMG quando utilizzo get_avatar?

Sto utilizzando un plug-in chiamato Simple Local Avatars che mi permette di caricare immagini dellautore che sono memorizzati sul mio server localmente (no Gravatar). Il plugin funziona bene e get_avatar restituisce lavatar locale.

Tuttavia, devo usare quellavatar in modi e luoghi diversi e per questo ho bisogno dellURL dellimmagine avatar locale invece dellintero tag HTML. Potrei scrivere una funzione wrapper per get_avatar che utilizza RegEx o SimpleXML per scegliere e restituire solo lURL, ma mi chiedevo se esiste un modo esistente per farlo.

Answer

Buone notizie per Versioni di WordPress 4.2+

Dalla versione 4.2 la pratica funzione get_avatar_url(), introdotta come richiesta di funzionalità nel ticket # 21195 pochi anni fa, ora viene fornito con il 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"]; } 

dove

get_avatar_data()è anche una nuova funzione di supporto.

Contiene questa parte di codice:

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

dove possiamo vedere che quando il parametro url è impostato, i filtri disponibili sono pre_get_avatar_data e get_avatar_data.

Dopo laggiornamento alla 4.2 di recente, ho avuto un problema con un tema che lo definiva la versione di get_avatar_url(), senza prefisso del nome della funzione o function_exists() controllo. Quindi questo è un esempio del motivo per cui è importante 😉

Risposta

La risposta sopra sembra completa, ma io ha scritto una funzione wrapper ed è andato avanti. Eccola qui se ne hai bisogno (mettila in functions.php):

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

e poi usalo ovunque ti serva nei file modello in questo modo:

<img src="<? echo get_avatar_url(get_avatar( $curauth->ID, 150 )); ?>" align="left" class="authorimage" /> 

È semplicemente più semplice.

Usare RegEx per analizzare HTML in questo caso va bene, perché questo analizzerà solo un tag img, quindi non sarà troppo costoso.

Commenti

  • Una piccola modifica … la funzione get_avatar inserisce src allinterno di ” non ‘ quindi la corrispondenza sarà nulla. Lespressione regolare dovrebbe essere preg_match (‘ / src = ” (. *?) ” / i ‘, $ get_avatar, $ corrispondenze);
  • grazie @spdaly – spero che commentando e autore da modificare;) – grazie aalaap
  • Se hai risposto alla tua domanda, contrassegnala come risposta accettata.
  • @Darth_Vader I haven ‘ Non ci sono tornato da quando ho postato la domanda, quindi ‘ non sono più sicuro che questo sia il modo ideale per farlo. Penso che la nuova risposta su 4.2+ sia migliore.

Answer

Puoi utilizzare il filtro get_avatar per ottenere tutti i dati nellavatar, anche lURL allinterno del markup. Penso che WP non abbia una funzione per restituire solo lURL se limmagine dellavatar.

$avatar = "<img alt="{$safe_alt}" src="{$default}" class="avatar avatar-{$size} photo avatar-default" height="{$size}" width="{$size}" />"; apply_filters("get_avatar", $avatar, $id_or_email, $size, $default, $alt); 

Inoltre puoi riscrivere questa funzione allinterno di un plugin o di un tema , la funzione è attiva solo se il nome della funzione non è definito in un altro luogo.

if ( ! function_exists( "get_avatar" ) ) : 

Quindi è possibile aggiungere un parametro per restituire solo lURL dellimmagine, in questo modo, usa il parametro $url con TRUE e ottieni solo lURL.

/** * Retrieve the avatar for a user who provided a user ID or email address. * * @since 2.5 * @param int|string|object $id_or_email A user ID, email address, or comment object * @param int $size Size of the avatar image * @param string $default URL to a default image to use if no avatar is available * @param string $alt Alternate text to use in image tag. Defaults to blank * @param boolean $url, true for get only the url of the image, no markup * @return string <img> tag for the user"s avatar */ function get_avatar( $id_or_email, $size = "96", $default = "", $alt = false, $url = FALSE ) { if ( ! get_option("show_avatars") ) return false; if ( false === $alt) $safe_alt = ""; else $safe_alt = esc_attr( $alt ); if ( !is_numeric($size) ) $size = "96"; $email = ""; if ( is_numeric($id_or_email) ) { $id = (int) $id_or_email; $user = get_userdata($id); if ( $user ) $email = $user->user_email; } elseif ( is_object($id_or_email) ) { // No avatar for pingbacks or trackbacks $allowed_comment_types = apply_filters( "get_avatar_comment_types", array( "comment" ) ); if ( ! empty( $id_or_email->comment_type ) && ! in_array( $id_or_email->comment_type, (array) $allowed_comment_types ) ) return false; if ( !empty($id_or_email->user_id) ) { $id = (int) $id_or_email->user_id; $user = get_userdata($id); if ( $user) $email = $user->user_email; } elseif ( !empty($id_or_email->comment_author_email) ) { $email = $id_or_email->comment_author_email; } } else { $email = $id_or_email; } if ( empty($default) ) { $avatar_default = get_option("avatar_default"); if ( empty($avatar_default) ) $default = "mystery"; else $default = $avatar_default; } if ( !empty($email) ) $email_hash = md5( strtolower( trim( $email ) ) ); if ( is_ssl() ) { $host = "https://secure.gravatar.com"; } else { if ( !empty($email) ) $host = sprintf( "http://%d.gravatar.com", ( hexdec( $email_hash[0] ) % 2 ) ); else $host = "http://0.gravatar.com"; } if ( "mystery" == $default ) $default = "$host/avatar/ad516503a11cd5ca435acc9bb6523536?s={$size}"; // ad516503a11cd5ca435acc9bb6523536 == md5("[email protected]") elseif ( "blank" == $default ) $default = includes_url("images/blank.gif"); elseif ( !empty($email) && "gravatar_default" == $default ) $default = ""; elseif ( "gravatar_default" == $default ) $default = "$host/avatar/?s={$size}"; elseif ( empty($email) ) $default = "$host/avatar/?d=$default&amp;s={$size}"; elseif ( strpos($default, "http://") === 0 ) $default = add_query_arg( "s", $size, $default ); if ( !empty($email) ) { $out = "$host/avatar/"; $out .= $email_hash; $out .= "?s=".$size; $out .= "&amp;d=" . urlencode( $default ); $rating = get_option("avatar_rating"); if ( !empty( $rating ) ) $out .= "&amp;r={$rating}"; if ( $url ) $avatar = $out; else $avatar = "<img alt="{$safe_alt}" src="{$out}" class="avatar avatar-{$size} photo" height="{$size}" width="{$size}" />"; } else { if ( $url ) $avatar = $out; else $avatar = "<img alt="{$safe_alt}" src="{$default}" class="avatar avatar-{$size} photo avatar-default" height="{$size}" width="{$size}" />"; } return apply_filters("get_avatar", $avatar, $id_or_email, $size, $default, $alt); } 

Unaltra piccola variante è che tu crea lURL con la regola di Gravatar.

function get_gravatar_url( $email ) { $hash = md5( strtolower( trim ( $email ) ) ); return "http://gravatar.com/avatar/" . $hash; } 

usalo sulla tua fonte con le email degli autori e ottieni lurl della sua immagine.

Risposta

Penso che questa sia una versione migliore 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] ); } 

Risposta

get_user_meta($userId, "simple_local_avatar"); 

Semplice Avatar locali utilizza i metacampi per memorizzare lavatar, quindi puoi semplicemente recuperare i valori chiamando get_user_meta e afferrando il campo “simple_local_avatar”. Ti verrà restituito un array in questo modo:

array ( [full] => "http://...", [96] => "http://...", [32] => "http://..." ) 

Risposta

Il metodo di alaap “non funziona più in WordPress 4.2

Ho trovato una soluzione. Eccolo e funziona bene:

 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; } 

nel modello usa semplicemente:

<?php my_gravatar_url() ?> 

Avviso: deve essere utilizzato allinterno di un ciclo.

Risposta

Quando lavatar è stato caricato localmente, WP, restituisce il tag img con lattributo src tra virgolette doppie, quindi Ho trovato che questo pattern funzionasse meglio:

preg_match("/src=["\"](.*?)["\"]/i", $get_avatar, $matches); 

Answer

Qualche ora fa , Mi chiedevo come farlo anchio. Ma presto ho trovato la soluzione e ho creato un plugin, controlla se get_avatar_url ($ user_id, $ size) funziona o no. Grazie ..

Codice plug-in:

/* 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" ); 

Utilizzo:

Richiamo della funzione:

get_avatar_url( get_the_author_meta( "user_email"), 150); 

Utilizzo dello shortcode:

do_shortcode("[avatar_url email="" . get_the_author_meta( "user_email") ."" size=150 ]" ); 

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *