Magento Product Social Media Marketing Part 1 – the Facebook Like Button

created February 23, 2011, last updated May 24, 2011.

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

What is Social Media Marketing? According to Wikipedia its “a means to gain customer and competitive insight, recruitment and retention of new customers/business partners, and a method of managing their reputation online.” It is a powerful way to create social exposure for your products and boost traffic to your site.

TwitterFacebook and Youtube are the most popular social networking destinations, I’ve already looked at how to automatically generate product marketing Tweets for Twitter, so let’s now turn our attention to Facebook and look at ways to integrate  product information from a Magento eCommerce store into the Facebook Social Graph by implementing the Facebook Like Button on all Magento product, category or cms pages.

You will have seen the Facebook Like Button everywhere, but what exactly is it? Facebook calls the Like Button a Social Plugin that “…lets a user share your content with friends on Facebook. When the user clicks the Like button on your site, a story appears in the user’s friends’ News Feed with a link back to your website.”  The Like Button is both simple and powerful. The concept is simple, Facebook users click the Like button to “like” something and indicate its cool to their friends. Their friends see the link they have liked in their Facebook news feed and are therfore also encouraged to click it. When the Like Button is integrated into your eCommerce store, the Facebook user (customer) indicates their confidence, satisfaction etc in your products by clicking the Like Button creating a great marketing opportunity for you by sharing your products with all of their friends. But there is more to it than that, because clicking the like button also integrates your product page into the Facebook “Open Graph” database.  Facebook says “If you include Open Graph tags on your Web page, your page becomes equivalent to a Facebook page. This means when a user clicks a Like button on your page, a connection is made between your page and the user. Your page will appear in the “Likes and Interests” section of the user’s profile, and you have the ability to publish updates to the user. Your page will show up in same places that Facebook pages show up around the site (e.g. search), and you can target ads to people who like your content.” Facebook is attempting to assimilate the Internet into its own Database ultimately turning all Internet pages into Facebook Open Graph objects. With a user base of around 400 million, whether you are a Facebook fan or not this marketing opportunity should not be neglected!

On Sunday 27th February 2011 Facebook altered the functionality of the Like button to replace the functionality of the Share button. The “Share” button will see no further development according to Facebook Spokeswoman Malorie Lucich. The company will continue to support the Share button but Like is the “recommended solution moving forward.” The main difference users will now see is that likes to external content are shown in profiles and news streams as “user likes a link TO EXTERNAL CONTENT” instead of “user likes EXTERNAL CONTENT”. The latter still applying for content hosted on Facebook.

Implementing the Like Button with Magento is relatively simple and there are extensions available from Magento Connect (even a free one!) the most important aspect of implementing the Like Button is getting the Open Graph data right to ensure that your products are “assimilated” correctly into Facebook with a unique and constant URL,  product title, image and meaningful SEO rich description. Check out the extensions with that in mind, if you want to implement the Like Button yourself within Magento 1.3, 1.4 or 1.5 here’s how I did it. I strongly recommend you develop your Facebook Like button on a development server and not your live site!

Go Canonical

The Like Button requires a unique URL to identify your product page in the Facebook Open Graph database.  Magento is notorious for creating duplicate content, generating mulitple URLs for the same product content so it is also good SEO practice to implement the canonical URL tag within the header of your site to tell search engines which URL they should use for your products to avoid duplicating search engine content. The canonical URL is perfect for the Facebook Open Graph URL tag. In Magento 1.4.x and above Canonical URLs are included in the core code, for Magento 1.3.x use the Yoast canonical URL extension its free and installs quickly and easily. Here’s how to install the extension under 1.3.

Magento Community Edition 1.3.x

You can find the Yoast canonical URL extension on Magento Connect note there are issues with this extension if you already use the Fooman Speedster module that you need to workaround.

I installed it under Magento 1.3.x using the command line PEAR installer :

dev/magento1-3-3-dev# ./pear mage-setup
Running initial setup...
config-set succeeded
Channel "connect.magentocommerce.com/core" is already initialized
Channel "connect.magentocommerce.com/community" is already initialized

dev/magento1-3-3-dev# ./pear install magento-community/canonical_url-1.3
downloading canonical_url-1.3.tgz ...
Starting to download canonical_url-1.3.tgz (3,866 bytes)
....done: 3,866 bytes
install ok: channel://connect.magentocommerce.com/community/canonical_url-1.3

Refresh the Magento cache to enable the extension.

Magento Community Edition 1.4.x, 1.5.x

Magento 1.4 and 1.5 now support the canonical tag “out of the box”. To enable the tag for the category and product pages go to: System=>Configuration=>Catalog=>Search Engine Optimization and enable: Use Canonical Link Meta Tag For Products (and if you want – Use Canonical Link Meta Tag For Categories) :

Enable canonical Meta Tag in Magento 1.4, 1.5
Enable canonical Meta Tag in Magento 1.4, 1.5

Confirm the Canonical Tag is correct

Check the Canonical Tag is working by browsing to a product and checking the source HTML. In my demo store with Magento 1.3.x or with the Canonical Tag option deactivated in Magento 1.4, 1.5 the Nokia 2610 product page shows the category/product url http://dev.webshop.com/electronics/cell-phones/nokia-2610-phone.html, with the Yoast extension or canonical Meta Tags activated there is a more SEO friendly canonical link URL :

<link rel=”canonical” href=”http://dev.webshop.com/nokia-2610-phone.html” />

Configure the Open Graph Meta tags

Now we have a static canonical URL for our products we need to configure the Open Graph meta tags Facebook will use to convert our page into a Facebook Open Graph object. Facebook says “The (Open Graph Meta) tags allow you to specify structured information about your web pages. The more information you provide, the more opportunities your web pages can be surfaced within Facebook today and in the future.”

Before we can add the meta tags we need to add the xmlns:fb -attribute to the xml name space element in our HTML header, this is so that Internet Explorer browsers can understand the Open Graph tags.

Locate the main /template/page folder for your Magento theme, for the default theme this is located in app/design/frontend/base/default/template/page for Magento 1.4.x, 1.5.x and app/design/frontend/default/default/template/page for Magento 1.3.x.

Open the main HTML template phtml file for your theme e.g. 2columns-right.phtml and locate the line of code with the opening HTML element:

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php echo $this->getLang() ?>" lang="<?php echo $this->getLang() ?>">

Change this to

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml" xmlns:og="http://opengraph.org/schema/" xml:lang="<?php echo $this->getLang() ?>" lang="<?php echo $this->getLang() ?>">

Now in the template/page/html folder open the head.phtml file and add the following code and Open Graph meta tags for your version of Magento directly under the existing META tags.  (Double click the code boxes and and use CTRL-C to copy the code.)

Magento Community Edition 1.3.x with Canonical URL Extension

<?php
/**
 * Facebook Open Graph meta tags Magento 1.3
 *
 */
?>
<!--Default OG Meta tags-->
<meta property="og:site_name" content="My eCommerce Store"/>
<meta property="og:street-address" content="1 THE High Street"/>
<meta property="og:locality" content="London"/>
<meta property="og:postal-code:" content="SW1"/>
<meta property="og:country-name:" content="United Kingdom"/>
<meta property="og:phone_number" content="00441234567890"/>
<meta property="og:latitude" content="00.00000000000000"/>
<meta property="og:longitude" content="00.00000000000000"/>
<?php // ***** Detect product or category page ?>
<?php if (Mage::registry('current_category')): ?>
<?php $cat=Mage::registry('current_category') ?>
<?php $catLevel=$cat->getLevel() ?>
<?php $catId=$cat->getId()  ?>
<?php $_id= Mage::app()->getRequest()->getParam('id', false)  ?>
<?php if($_id!=$catId):  ?>
<?php // Product page ?>
<!--Product page OG Meta tags-->
<meta property="og:title" content="<?php echo trim(Mage::registry('current_product')->getName())?>"/>
<meta property="og:type" content="product"/>
<?php if ($this->getHeadProductUrl()): ?>
<meta property="og:url" content="<?php echo $this->_data['urlKey'] ?>"/>
<?php endif; ?>
<meta property="og:description" content="<?php echo strip_tags(str_replace("<br />",", ",substr(Mage::registry('current_product')->getDescription(), 0, strpos(Mage::registry('current_product')->getDescription(), '.')+1))) ?>"/>
<meta property="og:image" content="<?php echo Mage::helper('catalog/image')->init(Mage::registry('current_product'), 'small_image')->resize(100,100);?>"/>
<?php else: ?>
<?php // Category page ?>
<!--Category page OG Meta tags-->
<meta property="og:title" content="<?php echo trim(Mage::registry('current_category')->getName())?>"/>
<meta property="og:type" content="product"/>
<meta property="og:url" content="<?php echo $this->helper('core/url')->getCurrentUrl() ?>"/>
<meta property="og:description" content="<?php echo htmlspecialchars($this->getDescription()) ?>"/>
<?php if(trim(Mage::registry('current_category')->getImageUrl()=="")): ?>
<meta property="og:image" content="CATEGORY HAS NO IMAGE CONFIGURE MANUAL LINK TO A GENERIC CATEGORY IMAGE"/>
<?php else: ?>
<meta property="og:image" content="<?php echo trim(Mage::registry('current_category')->getImageUrl())?>"/>
<?php endif; ?>
<?php endif; ?>
<?php endif; ?>
<?php // ***** Detect CMS page ?>
<?php if(Mage::getSingleton('cms/page')->getIdentifier() == 'home'  && Mage::app()->getFrontController()->getRequest()->getRouteName() == 'cms' ) : ?>
<!--Home page OG Meta tags-->
<meta property="og:title" content="THIS IS THE MAIN CMS HOME PAGE"/>
<meta property="og:type" content="product"/>
<meta property="og:url" content="<?php echo $this->helper('core/url')->getCurrentUrl() ?>"/>
<meta property="og:description" content="MY DESCRIPTION"/>
<meta property="og:image" content="MANUAL LINK TO A GENERIC IMAGE"/>
<?php endif; ?>

 

Magento Community Edition 1.4.x, 1.5.x

<?php
/**
 * Facebook Open Graph meta tags Magento 1.4, 1.5
 * updated 16.05.2011
 */
?>
<!--Default OG Meta tags-->
<meta property="og:site_name" content="My eCommerce Store"/>
<meta property="og:street-address" content="1 THE High Street"/>
<meta property="og:locality" content="London"/>
<meta property="og:postal-code:" content="SW1"/>
<meta property="og:country-name:" content="United Kingdom"/>
<meta property="og:phone_number" content="00441234567890"/>
<meta property="og:latitude" content="00.00000000000000"/>
<meta property="og:longitude" content="00.00000000000000"/>
<?php // ***** Detect product or category page ?>
<?php if (Mage::registry('current_category')): ?>
<?php $cat=Mage::registry('current_category') ?>
<?php $catLevel=$cat->getLevel() ?>
<?php $catId=$cat->getId()  ?>
<?php $_id= Mage::app()->getRequest()->getParam('id', false)  ?>
<?php if($_id!=$catId):  ?>
<?php // Product page ?>
<!--Product page OG Meta tags-->
<meta property="og:title" content="<?php echo trim(Mage::registry('current_product')->getName())?>"/>
<meta property="og:type" content="product"/>
<?php if ($this->helper('catalog/product')->canUseCanonicalTag()): ?>
<meta property="og:url" content="<?php echo trim(Mage::registry('current_product')->getProductUrl()) ?>"/>
<?php endif; ?>
<meta property="og:description" content="<?php echo strip_tags(str_replace("<br />",", ",substr(Mage::registry('current_product')->getDescription(), 0, strpos(Mage::registry('current_product')->getDescription(), '.')+1))) ?>"/>
<meta property="og:image" content="<?php echo Mage::helper('catalog/image')->init(Mage::registry('current_product'), 'small_image')->resize(100,100);?>"/>
<?php else: ?>
<?php // Category page ?>
<!--Category page OG Meta tags-->
<meta property="og:title" content="<?php echo trim(Mage::registry('current_category')->getName())?>"/>
<meta property="og:type" content="product"/>
<meta property="og:url" content="<?php echo $this->helper('core/url')->getCurrentUrl() ?>"/>
<meta property="og:description" content="<?php echo htmlspecialchars($this->getDescription()) ?>"/>
<?php if(trim(Mage::registry('current_category')->getImageUrl()=="")): ?>
<meta property="og:image" content="CATEGORY HAS NO IMAGE CONFIGURE MANUAL LINK TO A GENERIC CATEGORY IMAGE"/>
<?php else: ?>
<meta property="og:image" content="<?php echo trim(Mage::registry('current_category')->getImageUrl())?>"/>
<?php endif; ?>
<?php endif; ?>
<?php endif; ?>
<?php // ***** Detect CMS page ?>
<?php if(Mage::getSingleton('cms/page')->getIdentifier() == 'home'  && Mage::app()->getFrontController()->getRequest()->getRouteName() == 'cms' ) : ?>
<!--Home page OG Meta tags-->
<meta property="og:title" content="THIS IS THE MAIN CMS HOME PAGE"/>
<meta property="og:type" content="product"/>
<meta property="og:url" content="<?php echo $this->helper('core/url')->getCurrentUrl() ?>"/>
<meta property="og:description" content="MY DESCRIPTION"/>
<meta property="og:image" content="MANUAL LINK TO A GENERIC IMAGE"/>
<?php endif; ?>

First we add the site default OG Meta Tags including two Facebook tags to identify the Facebook admininstrator ID for this content and an associated Application ID. Add your Facebook account ID and app ID here. To register a Facebook application simply login to Facebook,  goto http://www.facebook.com/developers/apps.php and click on the “Set up new app” button. Give your app a name and set the domain name for the app – the domain name must match the domain the Like button is installed on for it to work, and save it. In the application settings or on the MyApp page you will see your Application ID number.

The information in these tags will be used by Facebook when they “scrape” your page the first time someone clicks on a product page Like Button.

Then we specify the Open Graph tags that will appear when we detect a product, category or cms pages. For CMS pages you need check for each CMS page name you wish to place a like button on, i.e. in the code example we are checking for a page called “home”. For CMS pages you need to also manually set the URL to an image. For category and sub category pages we can check for a configured category image, if non exists then use a manually configured default image. For products we will take the default image from the product. Bundled products are not currently being detected, will need to work on a solution for that…

If you want to include specific OG Meta tags for a page with a specific url then use.

<?php if($this->helper('core/url')->getCurrentUrl() === 'http://www.mystore.com/my-specific-page-url.htmll') : ?>
<!-- Specific Page OG Meta-->
<meta property="og:title" content="SPECIFIC PAGE OG CONTENT TITLE"/>
<meta property="og:type" content="product"/>
<meta property="og:url" content="<?php echo $this->helper('core/url')->getCurrentUrl() ?>"/>
<meta property="og:description" content="SPECIFIC PAGE CONTENT DESCRIPTION"/>
<meta property="og:image" content="http://www.mystore.com/myimage.jpg"/>
<?php endif; ?>

Edit the open graph data for your own requirements and add or remove more tags as you wish. The name, description and URL tags for product and category pages can be populated automatically. The URL for products comes from our canonical URL extension and the product description uses the same method I used for SEO description meta tags, to create a meaningful description to use within Facebook from the product long description text. The same method could be used for category pages too, for CMS pages you may need to manually enter the description for each CMS page you want a Like Button to appear on, and check for the page name using the code above.

More information on the Open Graph tags can be found here.

Save your files and refresh a product page. Check the source HTML to check that the Open Graph tags have been populated correctly for product, category, sub category and cms pages i.e. :

<!--Default OG Meta tags-->
<meta property="og:site_name" content="My eCommerce Store"/>
<meta property="og:street-address" content="1 THE High Street"/>
<meta property="og:locality" content="London"/>
<meta property="og:postal-code:" content="SW1"/>
<meta property="og:country-name:" content="United Kingdom"/>
<meta property="og:phone_number" content="00441234567890"/>

<meta property="og:latitude" content="00.00000000000000"/>
<meta property="og:longitude" content="00.00000000000000"/>
<!--Product page OG Meta tags-->
<meta property="og:title" content="Nokia 2610 Phone"/>
<meta property="og:type" content="product"/>
<meta property="og:url" content="http://dev150.webshop.com/nokia-2610-phone.html"/>
<meta property="og:description" content="The Nokia 2610 is an easy to use device that combines multiple messaging options including email, instant messaging, and more."/>
<meta property="og:image" content="http://dev150.webshop.com/media/catalog/product/cache/1/small_image/100x100/9df78eab33525d08d6e5fb8d27136e95/n/o/nokia-2610-phone-2.jpg"/>

Add the Magento Facebook Like Button – XFBML or IFrame?

Now we are all prepared to add our Like Button. You can render the Like Button and javascript code using two methods, XFBML or Iframe. There are pros and cons to both and you might already be averse to using Iframes on your pages. They both achieve the same result with the main difference being that the XFBML is slightly more versatile (and also perhaps quicker) allowing for a comment to be left after you have clicked the button, and also providing methods to trigger actions after the click.

Best practice recommends using XFBML but there is another reason for using the Iframe version that might interest you. If you sell the same product in multiple stores for example a Retail and a Wholesale store and the stores have different domains then using XFBML will result in two entries for the same product within Facebook because the domain name in the URL for the product must match the domain name of the page that executes the XFBML code. Using the Iframe method allows us to specify the domain ourselves and due to the nature of an Iframe Facebook has no way of confirming if it matches  the domain of the parent page of the Iframe or not. Another way to illustrate this is that if you develop your XFBML Facebook Like button on your development server and make test “Like” clicks on product X, Facebook will see this as http://your.develeopment.server/productX when you move the code to your live server, your “Likes” will be lost because Facebook will now register a new Open Graph object at http://your.live.server/productX. Whereas using the Iframe we can specify http://your.live.server/productX as the URL both on the live and development server.

Magento Facebook XFBML Like Button

Lets implement the XFBML version first. To add the Like Button to our product pages we need to locate view.phtml in the /template/catalog/product folder of our theme. Open view.phtml and look for the element or div that renders the product-name, around about line 50. We can locate the Facebook like button directly under the product name in the default theme, or you can locate it where you wish on your themes product page either by moving the code or positioning the button using a CSS class. Add the following code first :

<div id="facebook_like_product_button"><fb:like ref="product_page" layout="button_count" show_faces="false" colorscheme="light" width="500"></fb:like></div>

This defines how our button looks and there are various options that you can experiment with to get the button you want. Note the DIV ID (or class) can be changed/added to whatever you want to style or move the button within the page. Take a look at http://developers.facebook.com/docs/reference/plugins/like/ to experiment with the different button style options available. This is what they look like with standard, button count or box count layout styles :

Examples of different Like Button render options
Examples of different Like Button render options

Now we need to pull the Javascript SDK code from Facebook. Facebook says “The most efficient way to load the SDK in your site is to load it asynchronously so it does not block loading other elements of your page. This is particularly important to ensure fast page loads for users and SEO robots/spiders.” To access the SDK requires your Facebook application ID from Facebook. We can set the Like Button language with a locale code, add a translation for en_US to your Magento language files to change the language to match your store i.e. de_DE for German.

Add the following code next with your Facebook APP id, you can add it directly after the Button code on your product page if you will only be using like buttons on product pages. Or add it to your header.phtml template file to load it with every Magento page.

<!-- Facebook Like Product Button BEGIN - load the SDK asynchronously -->
	<div id="fb-root"></div>
		<script>
		/* <![CDATA[ */
			window.fbAsyncInit = function() {
			FB.init({appId: 'YOUR FACEBOOK APP ID', status: true, cookie: true,
				xfbml: true});
		};
		(function() {
			var e = document.createElement('script'); e.async = true;
			e.src = document.location.protocol +
			'//connect.facebook.net/<?php echo $this->__('en_US') ?>/all.js';
			document.getElementById('fb-root').appendChild(e);
		}());
		 /* ]]> */
		</script>
<!-- Facebook Like Product Button END -->

Notice that the Javascript code performs a protocol check to ensure that the link to Facebook matches the protocol of the page, i.e. HTTP or HTTPS, this is important when linking to external content to avoid browsers security errors when using an SSL connection.

Testing

Save your changes and refresh your product page to see your shiny new Like Button. Remember you should test all the popular browsers to ensure the code is working and the button displays correctly. Your browser tests should include, Internet Explorer, Firefox, Chrome, Opera and Safari and remember to test HTTPS access too. I also recommend that you check how your page looks to crawlers like Google Bot, an error in the header of your page may render ok for normal browsers but not for a crawler bot. You can also do a page fetch test from within Google Webmaster Tools. I learned this the hard way with a site becoming deindexed in Google due to a error in the header PHP code that was only being triggered by crawler Bots!

Like Button - Magento 1.3.x Product Page Example
Like Button - Magento 1.3.x Product Page Example

Go ahead and click on it (if you like it!) This will trigger Facebook to scrape your page and the “Like” should appear in your Facebook profile feed with the image, and title from your Open Graph tags.

Facebook Marketing Like - example news feed post
Facebook Marketing Like - example news feed post

To add the Like Button to a category page add the same Button code above to locate view.phtml in the /template/catalog/category folder of your theme. Open view.phtml and look for the element or div that renders the category-name and add the code just below it. Note that depending on your theme there will be multiple occurences of the category name for different category views in this file.

Magento Facebook Like button category page example
Magento Facebook Like button category page example

 

 

 

 

Remember for Facebook to scrape your page the URL must be valid and accessible from the Internet, so if you are working on a development server it must be also accessible from the Internet. It can take a while for the Open Graph data to be collected and to appear correctly in Facebook. If you want to manually check that your Open Graph data is accessible use the Facebook Lint tool at http://developers.facebook.com/tools/lint. Enter the canonical URL of a product page and Facebook will return the scraped Open Graph meta data for you to verify.

Verify Open Graph meta data with the Facebook Lint Tool
Verify Open Graph meta data with the Facebook Lint Tool

Magento Facebook IFrame Like Button

For completeness lets also look at implementing the Like Button using an IFrame, remember this can be useful because it allows cross domain Like buttons, i.e. buttons for the same content that will work when served from different website domains.

Unlike the XFBML code, the IFrame must specify the Like URL within the IFrame element so for Magento 1.3.x we need to generate the IFrame code in the header so that we can call the Canonical URL extension code. Add the following code at the end of head.phtml for Magento 1.3.x

<?php if (Mage::registry('current_product')) : ?>
<script type="text/javascript">
function fbLike(){
        return '<iframe src="http://www.facebook.com/plugins/like.php?href=<?php echo str_replace($this->getBaseUrl(),"http://www.YOUR-DOMAIN.com/",$this->_data['urlKey']) ?>&locale=<?php echo $this->__('en_US') ?>&layout=button_count&show_faces=false&width=150&action=like&colorscheme=light&height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:150px; height:21px;" allowTransparency="true"></iframe>';
    }
</script>
<?php endif; ?>

For Magento 1.4.x and 1.5.x you can either add the IFrame code directly to view.php or call it with the Javascript function in head.phtml. To use the Javascript function add the following to head.phtml

<?php if (Mage::registry('current_product')) : ?>
<script type="text/javascript">
function fbLike(){
        return '<iframe src="http://www.facebook.com/plugins/like.php?href=<?php echo str_replace($this->getBaseUrl(), "http://www.YOUR-DOMAIN.com/", trim(Mage::registry('current_product')->getProductUrl())); ?>&locale=<?php echo $this->__('en_US') ?>&layout=button_count&show_faces=false&width=150&action=like&colorscheme=light&height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:150px; height:21px;" allowTransparency="true"></iframe>';
    }
</script>
<?php endif; ?>

This code generates the IFrame html using a Javascript function that is called from the product page. Note that to keep the URL constant we replace the base host and domain name to be used for the Like Button with the domain name of the host site (or whatever we want). Edit www.YOUR-DOMAIN.com to match the URL of your site/store.

Now open up view.phtml and as with the XFBML solution add the following code after the product name, or wherever you want within the product view page of your theme.

<!-- Facebook Like Button BEGIN -->
<div id="fb-root"></div>
<script type="text/javascript">
document.write(fbLike());
</script>
<!-- Facebook Like Button END -->

This simply calls the Javascript function created in head.phtml which returns the HTML for the IFrame. For Magento 1.4, 1.5 you can also replace the script code directly with the IFrame code in view.phtml:

<!-- Facebook Like Button BEGIN -->
<div id="fb-root"></div>
<iframe src="http://www.facebook.com/plugins/like.php?href=<?php echo str_replace($this->getBaseUrl(), "http://www.YOUR-DOMAIN.com/", trim(Mage::registry('current_product')->getProductUrl())); ?>&locale=<?php echo $this->__('en_US') ?>&layout=button_count&show_faces=false&width=150&action=like&colorscheme=light&height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:150px; height:21px;" allowTransparency="true"></iframe>
<!-- Facebook Like Button END -->

Refresh the product page to see the IFrame version of the Like Button.

Positioning the Facebook Like Button

To style the button or to adjust its position on the product view page wrap the Facebook code in a DIV i.e. “facebook_like_product_button” and create a matching style CSS ID or class. For example to pad the button out a little add the following to your CSS:

/*Facebook Like Button*/
#facebook_like_product_button {
padding-top: 1em;
}

Like Button for your facebook page

If you want your main home page like button to Like an existing Facebook page simple modify the Like button code to include the URL of your Facebook page:

<fb:like href="http://www.facebook.com/YOUR.FACEBOOK.PAGE" ref="product_page" layout="button_count" show_faces="false" width="120"></fb:like>

Conclusions

Now that the like button is working you will want to check which products are receiving button clicks, use the Facebook Insight tool to look at the statistics for your product page Likes – http://www.facebook.com/insights/ You may need to first click the green “statistics for your domain” button to link your domain to your Facebook profile. You can also integrate reporting into Google Analytics, see the blog post below. Topics for another post include how to target customers that have liked your products individually by sending them specific product updates via Facebook.

Note that the code posted here was tested with Community Editions of Magento only.

In part two of this Social Media Marketing for Magento tutorial we will  integrate 300+ more Social Marketing destinations into Magento product pages using the AddThis toolbar.

More Reading

http://www.saschakimmel.com/2010/05/how-to-capture-clicks-on-the-facebook-like-button/

http://developers.facebook.com/docs/reference/plugins/like/

http://developers.facebook.com/docs/best-practices/

http://www.websharedesign.com/blog/how-do-i-track-that-little-facebook-like-button-in-google-analytics.html

http://developers.facebook.com/docs/opengraph/

http://garethhooper.com/articles/social-media/45-integration/158-how-to-correctly-add-the-facebook-social-plugins-to-your-website.html

Updated Facebook Like Button

http://soshable.com/facebook-like-butto

http://www.techi.com/2011/02/why-the-facebook-like-button-change-is-a-bait-and-switch/

http://davehiren.blogspot.com/2010/08/detect-product-page-in-magento.html

Comments

    • PAJ says:

      You need a Facebook app if you want to load the Facebook javascript SDK using the asynchronous method. You can also use a direct javascript link to the code however from my research the preferred method to avoid any problems with your page loading if the FB javascript cannot be loaded, i.e. problems with FB servers etc. is to use the asynchronous method.

  1. MPD says:

    Brilliant article!

    My site has images allocated to each category. Can you tell me the code to automatically put the link to that image in the og:image tag for categories?

    Thanks.

    • PAJ says:

      Try this

      Mage::registry(‘current_category’)->getImageUrl()

      I have noticed an error with certain sub categories that are also detected as product pages so will update my code and also include the code above for category images. Note this does not resize the image, but facebook may do that automatically.

  2. PAJ says:

    Post updated to include code for CMS, product and category page OG Tags including solutions for images, descriptions URLs etc. Please leave feedback if you find this solution useful.

  3. John says:

    I’m using 1.5.1 and I’ve turned on canonical in the admin, but it’s not working. First of all it seems like there’s a ” missing … but even when I add it the output looks like:

    meta property=”og:url” content=””

    any ideas on how to fix?

    • PAJ says:

      Yes I can see the problem too. Cant paste the code here so will update the blog post with the revised code. And there was a missing ” too, well spotted.

      May have found another problem detecting bundled product pages, will need to look into that some more.

  4. john says:

    boooooyah! That fixed it 🙂

    Mannnn, I should have just came here & asked you to look at it, spent 48 hours bangin my head trying to fix it myself 😛

    At least I have a MUCH better understanding of Magento 😛

  5. PAJ says:

    Hi, the code can’t produce a random pic, it product a link to the current product. Have a look at the HTML source to see the img link to the product, or use the Facebook Lint tool to look at your Open Graph tags.

  6. Eric says:

    Thanks for the article, it was incredibly helpful. I am however having one problem with the implementation on my development site and I can’t figure out the issue. The code adds the correct og: tags to all the product pages, but for some reason when I run the product url’s through the Facebook linter it isn’t recognizing the product specific og: tags. I carefully check all the code and can’t find any issues. Any help would be appreciated.

    • PAJ says:

      Hi Eric, if the site is public I will take a look at the html first and see if I can spot anything. Post the url here or email me at extensions at gaiterjones dot com

      Peter.

      • Eric says:

        Hi Peter, the url for the site is staging dot thepicketfence dot com and the like button should be up on all the product pages. Thanks for the help.

      • PAJ says:

        Which URL did you use when you registered your app id in facebook, did you use the staging hostname? I think the problem may lie there, everything else is correct and I have tested the OG tags with my own domain and app ID and the linter returns no errors, when I change to your url and app id, then I see the linter errors.

        Peter.

  7. nick says:

    Excellent tutorial. I have implemented open graph tags and the like button on other sites. For instantiating the button I have used

    which seems to alleviate the need for loading the asynchronous javascript SDK that you have shown.

    • PAJ says:

      Hi Nick, thanks for the comment, posting code in WordPress is not easy! Drop me an email with the code in if you like.

      Peter.

  8. Andrew says:

    I seem to be having some trouble getting this to work on the category pages. After clicking the like button, a box pops up where I can add a comment, but then it just disappears. Everything works fine on the product pages. Do you have any idea what might be causing this problem?

    • PAJ says:

      The best way to debug any problems with the Like button is to use the Facebook Lint tool to check that Facebook is seeing the OG data in your category page correctly. There is a link to the lint tool in the post.

  9. aronlee says:

    hi, i just have a question,i add the facebook like,but when i click the button “like”,the comment box pops up,but the image was not appear,but i really have added the image url in …sorry,my english is not good,hope you can understand what i say!thanks ..

    • PAJ says:

      Hi, use the Facebook Lint debug tool to check that your OG tags are correct. Simply goto the Facebook Lint page, paste the url to one of your product pages in and check that Facebook can scrape your page and display your OG information correctly. If all looks ok on the Lint page, then the Like button should work correctly.

  10. PAJ says:

    This module runs from a cron process within Magento, it’s not publicly web accessible in any way so regardless of the results shown the module is as secure as your Magento install is.

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