如何在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()orparseFloat():var transactionTotal = parseInt({{transactiontotal}}, 10); var shippingCosts = parseInt({{shippingcosts}}, 10); - Fallback Adjustment: The
return undefinedis a safe default, but you could return0or 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
相关产品推荐
相关产品推荐

