Integrating a Gravatar image into Magento

created February 2, 2011, last updated February 25, 2011.

closeThis post was last updated 11 years 10 months 18 days ago, some of the information contained here may no longer be actual and any referenced software versions may have been updated!

Gravatar (an abbreviation for globally recognized avatar) is a service for providing globally-unique avatars which was created by Tom Preston-Werner. Here is a simple way to integrate the Gravatar of a customer (if they have one) into your Magento eCommerce store to give a bit of an extra personal touch to your customers experience.

Magento shop header with integrated Customer Gravatar
Magento shop header with integrated Customer Gravatar (Magento 1.4.2)

This example will place the Gravatar image next to the welcome message in the shop header.

Open header.phtml located in your themes template/page/html/ folder and insert the following code:

 * Get a Gravatar Image URL
 * Set the parameters to create a Gravatar image request
 * create Gravatar img URL if a valid Gravatar exists.
 * PAJ 02.02.2011
$gravatar_img = '';
if (Mage::getSingleton('customer/session')->isLoggedIn()) {
	$gravatar_email = Mage::getSingleton('customer/session')->getCustomer()->getEmail();
	$gravatar_default = "404";
	$gravatar_rating = "g";
	$gravatar_size = 20;
	$gravatar_name = Mage::getSingleton('customer/session')->getCustomer()->getName();
	$gravatar_url = "" . md5( strtolower( trim( $gravatar_email ) ) ) . "?d=" . urlencode( $gravatar_default ) . "&s=" . $gravatar_size . "&r=" . $gravatar_rating;
	$gravatar_headers = get_headers($gravatar_url);
		if (!preg_match("|200|", $gravatar_headers[0])) {
			$gravatar_img = '';
		} else {
			$gravatar_img  = '<img src="'. $gravatar_url. '" title="'. $gravatar_name. '" alt="'. $gravatar_name. '" style="float:left" /> ';

Now look for the quick access DIV that calls the welcome message funtion getWelcome() and add in the Gravatar image URL. Note that Magento 1.4.2 adds some styling to the welcome message so you might want to style the Gravatar  too so it is placed better:

<?php echo $gravatar_img. $this->getWelcome() ?><br />

Thats it, the code uses the customers email address to create a valid MD5 encoded Gravatar image request, checks if a Gravatar exists and builds the URL to request the image in $gravatar_img. If a Gravatar exists it is displayed next to the welcome message and customers name. You could integrate the Gravatar elsewhere too, for example in the Customer Account Dashboard, or against customer comments, orders etc.

Further Gravatar development resources can be found here.
Tested with Magento 1.3.3  and 1.4.2.


This site uses Akismet to reduce spam. Learn how your comment data is processed.