Add Google AdWords Conversion Tracking (javascript) code into a PrestaShop / Smarty page

对着背影说爱祢 提交于 2019-12-03 21:32:35

It looks like I had to call getOrderTotal on the $cart object:

var google_conversion_value = {$cart->getOrderTotal(false, Cart::BOTH_WITHOUT_SHIPPING)};

First parameter is if you want to get the total with taxes or not. Second parameter is a constant in Cart.php:

const ONLY_PRODUCTS = 1;
const ONLY_DISCOUNTS = 2;
const BOTH = 3;
const BOTH_WITHOUT_SHIPPING = 4;
const ONLY_SHIPPING = 5;
const ONLY_WRAPPING = 6;
const ONLY_PRODUCTS_WITHOUT_SHIPPING = 7;
const ONLY_PHYSICAL_PRODUCTS_WITHOUT_SHIPPING = 8;

I'm afraid $cart->getOrderTotal() doesn't work this way because the $cart variable is set to null when arriving in order-confirmation.tpl. We have to find another way...

I found a way which is not very smart, but do the job so far. We have to call the Cart static method getTotalCart with the id_cart parameter. The problem is we don't have any smarty var with this parameter. The only way I found is to get it from the request URI.

So first, get the cart_id this way (using regex_replace):

{assign var='id_cart' value={$request_uri|regex_replace:"/.*id_cart=([\d]*).*/":"$1"}}

Then call the getTotalCart method with this parameter :

{$cart->getTotalCart($id_cart)|regex_replace:"/[\D]+.*/":""}

So the complete code is :

<script type="text/javascript"> 
    /* <![CDATA[ */ 

    {assign var='id_cart' value={$request_uri|regex_replace:"/.*id_cart=([\d]*).*/":"$1"}}

    {literal}
    var google_conversion_id = <my id>; 
    var google_conversion_language = "en"; 
    var google_conversion_format = "3"; 
    var google_conversion_color = "ffffff"; 
    var google_conversion_label = "<my label>"; 
    var google_conversion_value = {/literal}{$cart->getTotalCart($id_cart)|regex_replace:"/[\D]+.*/":""}{literal};{/literal}
    /* ]]> */ 
</script> 

It seems to work for me in prestashop v1.5.4

<script type="text/javascript">
/* <![CDATA[ */
{assign var='id_cart' value={$request_uri|regex_replace:"/.*id_cart=([\d]*).*/":"$1"}}
{assign var='total_cart' value={$cart->getTotalCart($id_cart)|regex_replace:"/[\D]+.*/":""}}
{literal}
var google_conversion_id = YOUR_CONVERSION_ID;
var google_conversion_language = "en"; // or your language iso
var google_conversion_format = "3"; // or your format
var google_conversion_color = "ffffff";
var google_conversion_label = "YOUR_CONVERSION_LABEL";
var google_conversion_value = {/literal}{$total_cart}{literal};{/literal}
/* ]]> */
</script>
<script type="text/javascript" src="//www.googleadservices.com/pagead/conversion.js">
</script>
<noscript>
<div style="display:inline;">
<img height="1" width="1" style="border-style:none;" alt="" src="//www.googleadservices.com/pagead/conversion/YOUR_CONVERSION_ID/?value={$total_cart}&amp;label=YOUR_CONVERSION_LABEL&amp;guid=ON&amp;script=0"/>
</div>
</noscript>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!