Twitter Cards & Magento

Twitter cards offer rich ways to share content from websites. Here’s how to implement Twitter’s card data and add a share link to product pages!

Create A Head Block

This will allow us to implement Twitter’s meta tags into Magento’s head block. Creating this as a text list will also allow us to reuse this for pages other than product detail.

<default>
    <reference name="head">
        <block type="core/text_list" name="twitter.head.extra" />
    </reference>
</default>

Add The Meta Card Data

<catalog_product_view>
    <reference name="twitter.head.extra">
        <block type="modulename/catalog_product_view_meta" name="twitter.product.meta" template="catalog/product/view/meta.phtml" />
    </reference>
</catalog_product_view>

Create The Meta Template

Create this in the location catalog/product/view/meta.phtml

<?php
$_imageUrl = $this->getImageUrl();
$_product = $this->getProduct();

?>
<?php if($_imageUrl): ?>
    <meta name="twitter:card" content="summary" />
    <meta name="twitter:image" content="<?php echo $_imageUrl; ?>">
    <meta name="twitter:site" content="@twitter_handle" />
    <meta name="twitter:title" content="<?php echo $this->htmlEscape($_product->getName()); ?>" />
    <meta name="twitter:description" content="<?php echo $this->htmlEscape($_product->getShortDescription()); ?>" />
<?php endif; ?>

Create The Block Class

This is the class we reference in our XML and should correspond to modulename/catalog_product_view_meta

<?php
class Namespace_Module_Block_Catalog_Product_View_Meta extends Mage_Core_Block_Template
{
    protected function getProduct()
    {
        return Mage::registry('product');
    }

    public function getImageUrl()
    {
        if(!($product = $this->getProduct())){
            return;
        }

        return Mage::helper('catalog/image')->init($product, 'small_image');
    }
}

Add A Sharing Link

If the above steps are working correctly, all of the product meta tags included in the head of the product page’s head. Now, we just nee to create a sharing link from the page and Twitter should do the rest for us!

<?php 
$_product = $this->getProduct();
$_helper = $this->helper('catalog/output');
$_productName = urlencode(trim($_helper->productAttribute($_product, $_product->getName(), 'name')));
$_productUrl = urlencode(trim($_product->getProductUrl()));
?>

<a class="icon icon-twitter" href="<?php echo 'http://twitter.com/home?status=' . $_productName . "  " . $_productUrl; ?>" target="_blank" title="<?php echo Mage::helper('core')->quoteEscape($this->__('Share on Twitter')) ?>">
    <span><?php echo $this->__('Share on Twitter') ?></span>
</a>