Comment obtenir lURL de lavatar au lieu dune balise HTML IMG lorsque jutilise get_avatar?

Jutilise un plugin appelé Avatars locaux simples qui me permet de télécharger des images dauteur qui sont stockés localement sur mon serveur (pas de Gravatar). Le plugin fonctionne bien et get_avatar renvoie lavatar local.

Cependant, je dois utiliser cet avatar dans différentes manières et différents endroits et pour cela jai besoin de lURL de limage de lavatar local au lieu de la balise HTML entière. Je pourrais écrire une fonction wrapper pour get_avatar qui utilise RegEx ou SimpleXML pour sélectionner et renvoie uniquement lURL, mais je me demandais sil existe un moyen de le faire.

Réponse

Bonne nouvelle pour Versions de WordPress 4.2+

Depuis la version 4.2, la fonction get_avatar_url() pratique, introduite comme une demande de fonctionnalité dans le ticket # 21195 il y a quelques années, est désormais livré avec le noyau :

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

get_avatar_data()est également une nouvelle fonction daide.

Elle contient cette partie 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ù nous pouvons voir que lorsque le paramètre url est défini, les filtres disponibles sont pre_get_avatar_data et get_avatar_data.

Après la mise à jour vers 4.2 récemment, jai eu un problème avec un thème qui définissait sa propre version de get_avatar_url(), sans préfixe de nom de fonction ni vérification function_exists(). Voici donc un exemple de la raison pour laquelle cest « important 😉

Réponse

La réponse ci-dessus semble complète, mais je a écrit une fonction wrapper et a continué. Le voici si vous en avez besoin (mettez ceci dans functions.php):

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

puis utilisez-le partout où vous en avez besoin dans les fichiers modèles comme celui-ci:

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

Cest juste plus simple.

Utilisation RegEx pour analyser le HTML dans ce cas est correct, car cela ne sera analysé quune seule balise img, donc cela ne sera « pas trop coûteux.

Commentaires

  • Un petit changement … la fonction get_avatar place le src dans  » pas ‘ donc la correspondance sera nulle. Lexpression régulière doit être preg_match (‘ / src =  » (. *?)  » / i ‘, $ get_avatar, $ matches);
  • merci @spdaly – jespère que les commentaires le rendraient e author to edit;) – merci aalaap
  • Si vous avez répondu à votre propre question, veuillez la marquer comme réponse acceptée.
  • @Darth_Vader I havre ‘ Jy suis retourné depuis que jai posté la question, donc je ‘ ne sais plus si cest la manière idéale de le faire. Je pense que la nouvelle réponse sur 4.2+ est meilleure.

Réponse

Vous pouvez utiliser le filtre get_avatar pour obtenir toutes les données de lavatar, ainsi que lurl à lintérieur du balisage. Je pense que WP na pas de fonction pour renvoyer uniquement lurl de limage de lavatar.

$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); 

Vous pouvez également réécrire cette fonction dans un plugin ou un thème , la fonction est uniquement active, si ce nom de fonction nest pas défini à un autre endroit.

if ( ! function_exists( "get_avatar" ) ) : 

Il est donc possible dajouter un paramètre pour ne renvoyer que lurl de limage, comme ceci, utilisez le paramètre $url avec TRUE et vous obtenez uniquement 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); } 

Une autre petite variante est que vous créez lurl avec la règle de Gravatar.

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

utilisez ceci sur votre source avec les e-mails des auteurs et vous obtenez lurl de leur image.

Réponse

Je pense que cest une meilleure version de la réponse daalaap:

// 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] ); } 

Réponse

get_user_meta($userId, "simple_local_avatar"); 

Simple Avatars locaux utilise des méta-champs pour stocker lavatar, vous pouvez donc simplement récupérer la ou les valeurs en appelant get_user_meta et saisissez le champ « simple_local_avatar ». Vous « obtiendrez un tableau comme celui-ci:

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

Réponse

La méthode dalaap ne fonctionne plus sous WordPress 4.2

Jai trouvé une solution. Le voici et ça marche bien:

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

Réponse

Lorsque lavatar a été téléchargé localement, WP, renvoie la balise img avec lattribut src entre guillemets, donc Jai trouvé que ce modèle fonctionnait mieux:

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

Réponse

Il y a quelques heures , Je me demandais comment faire ça aussi. Mais, bientôt jai eu la solution et créé un plugin, veuillez vérifier si get_avatar_url ($ user_id, $ size) fonctionne pour vous ou non. Merci ..

Code du plugin:

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

Utilisation:

Appel de la fonction:

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 ]" ); 

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *