I have a problem I've been struggling for a couple of days and I would really like you to point me in the right direction. I am developing a module to track basic stuff like addToCart and ViewContent for the Facebook pixel.
The problem is, my module cannot track Ajax addToCart event using extensions like this. I would really like you to give me some proper directions cause I feel like I am really lost in this one.
I tried updating layouts, adding my block on my observer event and much more. I'll pass some of my code below so you can get an idea of what I'm trying to do.
config.xml
<frontend>
<routers>
<advertising>
<use>standard</use>
<args>
<module>My_Advertising</module>
<frontName>my</frontName>
</args>
</advertising>
</routers>
<events>
<checkout_cart_product_add_after>
<observers>
<advertising>
<class>advertising/observer</class>
<method>myAddToCart</method>
</advertising>
</observers>
</checkout_cart_product_add_after>
</events>
<layout>
<updates>
<advertising>
<file>advertising.xml</file>
</advertising>
</updates>
</layout>
Observer function that I'm setting a variable for the product that has been added to cart
public function myAddToCart($observer)
{
$product = Mage::getModel('catalog/product')
->load(Mage::app()->getRequest()->getParam('product', 0));
if (!$product->getId()) {
return;
}
Mage::getModel('core/session')->setProductToShoppingCart(
new Varien_Object(array(
'id' => $product->getSku(),
'name' => $product->getName(),
'brand' => $product->getAttributeText('manufacturer'),
'price' => $product->getPrice(),
'qty' => Mage::app()->getRequest()->getParam('qty', 1),
'currency' => Mage::app()->getStore()->getCurrentCurrencyCode(),
))
);
}
layout file
<?xml version="1.0" encoding="UTF-8"?>
<layout version="0.1.0">
<checkout_cart_add>
<reference name="content">
<block type="advertising/Mytracking" name="advertising_mytrackingcart" template="advertising/mytrackingcart.phtml">
</block>
</reference>
</checkout_cart_add>
</layout>
mytrackingcart.phtml
<?php $product = Mage::getModel('core/session')->getProductToShoppingCart(); ?>
<?php if ($product && $product->getId()): ?>
<script type="text/javascript">
echo $this->myGetAddToCartFacebook($product);
</script>
<?php Mage::getModel('core/session')->unsProductToShoppingCart(); ?>
<?php endif; ?>
My block function
public function myGetAddToCartFacebook()
{
$id = $product['id'];
$price = number_format($product['price'], 2);
$currency = $product['currency'];
$code = "fbq('track', 'AddToCart', { value: \"{$price}\",currency: \"{$currency}\",content_ids: [\"{$id}\"],content_type: 'product' });";
return $code;
}
onclick
before the actual add to cart happens?