You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Google Tag Manager中对两个数据层变量计算生成新变量

How to Create a Calculated Integer Variable in Google Tag Manager

Hey there! I’ve got you covered on this—calculating a new variable by subtracting two integer data layer values in GTM is totally achievable with a Custom JavaScript variable. Here’s a step-by-step breakdown to set it up:

  • Head to your GTM workspace, then go to Variables > New (under the User-Defined Variables section).
  • Select the Custom JavaScript variable type from the available options.
  • Name your variable clearly, like transactiontotalexcludingshipping.
  • Paste this code into the JavaScript editor, making sure to reference your existing data layer variables correctly:
    function() {
      // Pull in your existing data layer variables
      var transactionTotal = {{transactiontotal}};
      var shippingCosts = {{shippingcosts}};
      
      // Validate both values are numbers to prevent errors
      if (typeof transactionTotal === 'number' && typeof shippingCosts === 'number') {
        return transactionTotal - shippingCosts;
      }
      // Fallback if either variable isn't a valid number (adjust as needed)
      return undefined;
    }
    
  • Save the variable. You can now use {{transactiontotalexcludingshipping}} in your tags or triggers just like any other GTM variable.

Key Tips to Avoid Issues:

  • String-to-Number Conversion: If your data layer sometimes passes these values as strings (even if they look like integers), convert them first using parseInt() or parseFloat():
    var transactionTotal = parseInt({{transactiontotal}}, 10);
    var shippingCosts = parseInt({{shippingcosts}}, 10);
    
  • Fallback Adjustment: The return undefined is a safe default, but you could return 0 or another value if that better fits your tracking requirements.
  • Test Thoroughly: Use GTM’s Preview mode to confirm the variable calculates correctly. Check the Variables tab in Preview to verify the new value appears as expected when a transaction fires.

内容的提问来源于stack exchange,提问作者Robbert Smit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:45:57