Fix Open Graph Problem in Magento 1.8 and 1.9

magento-1.8magento-1.9open-graph

While creating Open Graph extension in Magento I came across an issue- although my metatag is correct, facebook cannot catch my og tag because there is too much code before my meta/og tag.

Has anyone else encountered this and do you have any suggestions?

<reference name="head">
    <block type="catalog/product_view" name="product.opengraph">
        <action method="setTemplate">
            <template>socialtag/opengraph_product.phtml</template>
        </action>
    </block>      
</reference>

Best Answer

Here's an alternative solution. It's not nice, and should be considered a hack. It also goes against the purposes of Magento's layout system. Nonetheless, if your requirement is not to override the base head template, then try this:

Inject Content via Event Observer

In your module config XML, add the following event:

...
<global>
    ...
    <events>
        <http_response_send_before>
            <observers>
                <head_modify>
                    <type>singleton</type>
                    <class>Namespace_Module_Model_Observer</class>
                    <method>injectOgTags</method>
                </head_modify>
            </observers>
        </http_response_send_before>
    </events>
    ...
</global>
...

And then you would create an observer class to match:

<?php

class Namespace_Module_Model_Observer
    extends Varien_Event_Observer
{

    public function injectOgTags(Varien_Object $object)
    {
        $response   = $object->getResponse();
        $html       = $response->getBody();

        // Some logic for building up the appropriate meta tags
        // based on URL or product or layout handles
        $html = str_replace('<head>', '<head><meta property="og:title" content="Page title" />', $html);

        $response->setBody($html);
    }

}

So far as I can see, this is only way to solve your problem. Neither the stock head block nor its base template make provisions for adding meta tags above its call for child HTML.

Related Topic