I implemented a custom script in tankyou page in my woocommerce store to track google ads conversions. This is my implementation:
add_action( "woocommerce_thankyou", "pixel_analytics_conversion_track_script", 20 );
if ( ! function_exists( 'pixel_analytics_conversion_track_script' ) ) {
function pixel_analytics_conversion_track_script( $order_id ) {
if ( $order_id > 0 ) {
$order = wc_get_order( $order_id );
if ( $order instanceof WC_Order ) {
$order_id = $order->get_id(); // order id
$order_key = $order->get_order_key(); // order key
$order_total = $order->get_total(); // order total
$order_currency = $order->get_currency(); // order currency
$order_payment_method = $order->get_payment_method(); // order payment method
$order_shipping_country = $order->get_shipping_country(); // order shipping country
$order_billing_country = $order->get_billing_country(); // order billing country
$order_status = $order->get_status(); // order status
?>
<script type="text/javascript">
jQuery(document).ready(function( $ ){
console.log('PURCHACE EVENT');
/* Track conversion on facebook Pixel */
fbq('track', 'Purchase',
{
value: <?php echo $order_total ?>,
currency: "<?php echo $order_currency ?>"
});
/* Track conversion on Google Ads */
gtag('event', 'conversion',
{
'send_to': 'AW-693771414/0MhwCMa9rLYBEJa56MoC',
'value': <?php echo $order_total ?>,
'currency': "<?php echo $order_currency ?>",
'transaction_id': "<?php echo $order_id ?>"
});
});
</script>
<?php
}
}
}
}
The code works very well but some data is not precise and I think that probably the code above duplicates conversion if user goes to thank you page twice. We have an order confirmation email that has a link to the thankyou page of woocommerce.
As you can see Im sending the transaction_id parameter, so my question:
If the user loads twice or N times the thank you page the conversion will appear dupplicated in Google ads even if you send the transaction_id parameter?
You can use order custom meta data to avoid duplicated Conversion tracking as follows:
add_action( "woocommerce_thankyou", "pixel_analytics_conversion_track_script", 20 );
if ( ! function_exists( 'pixel_analytics_conversion_track_script' ) ) {
function pixel_analytics_conversion_track_script( $order_id ) {
// Avoid if pixel analytics conversion track script has been run before
if ( $order_id > 0 && 'done' !== get_post_meta( $order_id, '_pixel_tracking', true ) ) {
$order = wc_get_order( $order_id );
if ( is_a($order, 'WC_Order') ) {
$order_id = $order->get_id(); // order id
$order_key = $order->get_order_key(); // order key
$order_total = $order->get_total(); // order total
$order_currency = $order->get_currency(); // order currency
$order_payment_method = $order->get_payment_method(); // order payment method
$order_shipping_country = $order->get_shipping_country(); // order shipping country
$order_billing_country = $order->get_billing_country(); // order billing country
$order_status = $order->get_status(); // order status
?>
<script type="text/javascript">
jQuery(document).ready(function( $ ){
console.log('PURCHACE EVENT');
/* Track conversion on facebook Pixel */
fbq('track', 'Purchase',
{
value: <?php echo $order_total ?>,
currency: "<?php echo $order_currency ?>"
});
/* Track conversion on Google Ads */
gtag('event', 'conversion',
{
'send_to': 'AW-693771414/0MhwCMa9rLYBEJa56MoC',
'value': <?php echo $order_total ?>,
'currency': "<?php echo $order_currency ?>",
'transaction_id': "<?php echo $order_id ?>"
});
});
</script>
<?php
// Flag the order (with custom meta data) to avoid pixel analytics conversion track script run multiple times.
update_post_meta( $order_id, '_pixel_tracking', true );
}
}
}
}
Code goes in functions.php file of the active child theme (or active theme). It should works.
Related
I'm trying to put order id and value to tracking code but can't make it work. I tried to put there
$order_id = $order->get_id();
$order->get_id();
$order->get_total();
and nothing works. Here's code and places where I need these elements:
<script language="JavaScript">
tdconv('init', '2253741', {'element': 'iframe' });
tdconv('track', 'sale', {'transactionId':'ORDER ID HERE', 'ordervalue':ORDER VALUE HERE, 'currency':'PLN', 'event':400532});
</script>
Can anyone give me some tips?
Here is the way to get order data for a javascript tracking script from order received page (thankyou):
add_action( 'wp_footer', 'thankyou_tracking_script_js' );
function thankyou_tracking_script_js(){
// Order reveived / thankyou page
if ( ! is_wc_endpoint_url( 'order-received' ) ) return;
global $wp;
// If order_id is defined
if ( isset($wp->query_vars['order-received']) && absint($wp->query_vars['order-received']) > 0 ) :
$order_id = absint($wp->query_vars['order-received']); // The order ID
$order = wc_get_order( $order_id ); // The WC_Order object
$transaction_id = empty($order->get_transaction_id()) ? $order_id : $order->get_transaction_id(); // The transaction ID
?>
<script language="JavaScript">
tdconv('init', '2253741', {'element': 'iframe' });
tdconv('track', 'sale', {
'transactionId' : '<?php echo $transaction_id; ?>',
'ordervalue' : '<?php echo $order->get_total(); ?>',
'currency' : '<?php echo $order->get_order_currency(); ?>',
'event' : 400532
});
</script>
<?php
endif;
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
Related:
How to get WooCommerce order details
Tracking Add too cart & submit Order for Facebook Pixel In WooCommerce
Conditional Logic and custom FB Pixels Integration into WooCommerce
I'm trying to add some google tracking script to my thank you page. I've written this code which successfully injects the tracker into the of the thank you with dynamic values, but I need, instead, to add it within the tags.
function mv_google_conversion( $order_id ) {
$order = new WC_Order( $order_id );
$currency = $order->get_currency();
$total = $order->get_total();
?>
<script>
gtag('event', 'conversion', {
'send_to': 'AW-746876528/x5W1CLfA8JoBEPDckeQC',
'value': <?php echo $total; ?>,
'currency': '<?php echo $currency; ?>',
'transaction_id': '<?php echo $order_id; ?>'
});
</script>
<?php
}
add_action( 'woocommerce_thankyou', 'mv_google_conversion' );
How would I be able to use this code, with the dynamic values in header.php, or is there a hook that targets the tags on the woocommerce thank you page.
You will use the following to inject code on the head tags on "Order received" (thankyou) page:
add_action( 'wp_head', 'my_google_conversion' );
function my_google_conversion(){
// On Order received endpoint only
if( is_wc_endpoint_url( 'order-received' ) ) :
$order_id = absint( get_query_var('order-received') ); // Get order ID
if( get_post_type( $order_id ) !== 'shop_order' ) return; // Exit
$order = wc_get_order( $order_id ); // Get the WC_Order Object instance
?>
<script>
gtag('event', 'conversion', {
'send_to': 'AW-746876528/x5W1CLfA8JoBEPDckeQC',
'value': <?php echo $order->get_total(); ?>,
'currency': '<?php echo $order->get_currency(); ?>',
'transaction_id': '<?php echo $order_id; ?>'
});
</script>
<?php
endif;
}
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
IN Woocommerce, I use Header & Footer plugin to add on body tag a tracking affiliate code for the whole site.
The code is:
<script async src="//go.linkwi.se/delivery/js/tl.js"></script>
<script>
window.lw=window.lw||function(){(lw.q=lw.q||[]).push(arguments)};lw.l=+new Date;
lw("setProgram", "12838");
lw("setDecimal", ".");
</script>
My affiliate partner ask me the code be disabled from woocommerce thank you page (according the image - Line935 to 940).
woocommerce thank you page source code:
I think I need to add_filter action or something to disable it.
Any help will be useful for this.
UPDATE: If I remove the code from Header & Footer plugin is disabled from the whole site.
Instead of using a plugin, use the following to avoid your script to be loaded on thankyou page.
You have 2 choices:
1) On Footer (the best choice, I think):
add_action( 'wp_footer' , 'linkwi_delivery_script' );
function linkwi_delivery_script(){
// Not on thankyou page
if( is_wc_endpoint_url('order-received') ) return;
?>
<script async src="//go.linkwi.se/delivery/js/tl.js"></script>
<script>
window.lw=window.lw||function(){(lw.q=lw.q||[]).push(arguments)};lw.l=+new Date;
lw("setProgram", "12838");
lw("setDecimal", ".");
</script>
<?php
}
2) On Header:
add_action( 'wp_head' , 'linkwi_delivery_script' );
function linkwi_delivery_script(){
// Not on thankyou page
if( is_wc_endpoint_url('order-received') ) return;
?>
<script async src="//go.linkwi.se/delivery/js/tl.js"></script>
<script>
window.lw=window.lw||function(){(lw.q=lw.q||[]).push(arguments)};lw.l=+new Date;
lw("setProgram", "12838");
lw("setDecimal", ".");
</script>
<?php
}
Code goes in function.php file of your active child theme (or active theme). It should works.
So finaly my code in child function.php it look like this.
// Utility function that contain Linkwise Affiliate script
function linkwise_affiliate_scripts( $order_id ){
## --- YOUR SETTINGS START BELOW --- ##
$program_id = '12838'; // <== Your program number
$decimal_sep = '.'; // Decimal separator
$currency = '978'; // For "EUR" => See: https://en.wikipedia.org/wiki/ISO_4217
## --- END SETTINGS --- ##
$order = wc_get_order( $order_id );
$order_status = $order->get_status();
$items_string = array();
$count = 0;
?>
<script async src="//go.linkwi.se/delivery/js/tlwt.js"></script>
<script>
window.lw=window.lw||function(){(lw.q=lw.q||[]).push(arguments)};
lw .l=+new Date;
lw("setProgram", "<?php echo $program_id; ?>");
lw("setDecimal", "<?php echo $decimal_sep; ?>");
</script>
<script>
lw("setCurrency", "<?php echo $currency; ?>"); // Set your currency
<?php
foreach( $order->get_items() as $item ):
$count++;
$item_id = $item->get_id(); // The item ID
// Get an instance of the WC_Product object
$product = $item->get_product();
$product_id = $item->get_product_id(); // Product ID
$price_excl_vat = wc_get_price_excluding_tax( $product ); // Unit price excluding VAT
$item_qty = $item->get_quantity(); // Item quantity
$payout = '1'; // (???)
// The string for the <noscript> at the bottom
$items_string[] = "itemid[$count]=$item_id&itemprice[$count]=$price_excl_vat&itemquantity[$count]=$item_qty&a
mp;itempayout[$count]=$payout";
?>
lw("addItem", {
id: "<?php echo $item_id; // Or can be the product ID (may be) ?>"
,price: "<?php echo $price_excl_vat; ?>"
,quantity: "<?php echo $item_qty; ?>"
,payout: "<?php echo $payout; ?>"
});
<?php
endforeach;
// Set the array of items strings in a unique string
$items_string = implode( '&', $items_string );
?>
// Other items types
<?php
$coupon_discounts = $coupon_discounts_tax = 0;
foreach( $order->get_items('coupon') as $item_coupon ){
$coupon_discounts += $item_coupon->get_discount();
$coupon_discounts_tax += $item_coupon->get_discount_tax();
}
?>
lw("setCoupon", "<?php echo $coupon_discounts; ?>");
lw("thankyou", {
orderid: "<?php echo $order_id; ?>"
,status: "<?php echo $order_status; ?>"
});
</script>
<noscript>
<img
src="//go.linkwi.se/delivery/acl.php?program=<?php echo $program_id; ?>&decimal=<?php echo $decimal_sep; ?>&<?php echo $items_string; ?>&coupon_price=<?php echo $coupon_discounts; ?>&status=<?php echo $order_status; ?>&orderid=<?php echo $order_id; ?>" style="width:0px;height:0px;"/>
</noscript>
<?php echo 'test';
}
add_filter( 'wp_footer', 'wc_linkwise_affiliate_order_received_integration' );
function wc_linkwise_affiliate_order_received_integration() {
if ( ! is_wc_endpoint_url( 'order-received' ) )
return; // Exit
global $wp;
$order_id = absint( $wp->query_vars['order-received'] );
if ( empty($order_id) || $order_id == 0 )
return; // Exit
linkwise_affiliate_scripts( $order_id ); // Run the Linkwise Affiliate
}
add_action( 'wp_footer' , 'linkwi_delivery_script' );
function linkwi_delivery_script(){
// Not on thankyou page
if( is_wc_endpoint_url('order-received') ) return;
?>
<script async src="//go.linkwi.se/delivery/js/tl.js"></script>
<script>
window.lw=window.lw||function(){(lw.q=lw.q||[]).push(arguments)};lw.l=+new Date;
lw("setProgram", "12838");
lw("setDecimal", ".");
</script>
<?php
}
I have a custom thank you page for after checkout is finished in WooCommerce where I need to insert order data into a Google ecommerce tracking tag to record the sale in analytics. One part of that is adding the following for each item in the order...
ga('ecommerce:addItem', {
'id': <?php echo $order_id?>, // Transaction ID. Required.
'name': 'ACME Product', // Product name. Required.
'sku': '1234', // SKU/code.
'category': 'Product Category', // Category or variation.
'price': '10.00', // Unit price.
'quantity': '1' // Quantity.
});
but with inserting the order item's real data using PHP, not the placeholders you see there for name, sku, category, price, and quantity.
In Googling around for answers, I see that I must now use
wc_display_item_meta ( $item ); rather than the deprecated $item_meta = new WC_Order_Item_Meta( $item['item_meta'], $_product );
What I need help with, because I don't yet fully know PHP and I can't seem to find any close examples, is how do I begin to grab the values? Is it a foreach of some kind, or is there a way to directly parse out each item's individual properties out of the order item into a variable that I can then insert in these placeholders?
Try the following (you may have to make some changes and add the affiliation Id):
?>
<script>
ga('require', 'ecommerce');
<?php
// GET the WC_Order object instance from, the Order ID
$order = wc_get_order( $order_id );
$order_key = $order->get_order_key();
$transaction_id = $order->get_transaction_id(); // Doesn't always exist
$transaction_id = $order_id; // (Or the order key or the transaction ID if it exist)
?>
ga('ecommerce:addTransaction', {
'id': '<?php echo $transaction_id; // To be checked ?>',
'affiliation': '<?php echo 'UA-XXXXX-Y'; // replace by yours ?>',
'revenue': '<?php echo $order->get_total(); ?>',
'shipping': '<?php echo $order->get_shipping_total(); ?>',
'tax': '<?php echo $order->get_total_tax(); ?>',
'currency': '<?php echo get_woocommerce_currency(); // Optional ?>'
}); <?php
// LOOP START: Iterate through order items
foreach( $order->get_items() as $item_id => $item ) :
// Get an instance of the WC_Product object
$product = $item->get_product();
// Get the product categories for the product
$categories = wp_get_post_terms( $item->get_product_id(), 'product_cat', array( 'fields' => 'names' ) );
$category = reset($categories); // Keep only the first product category
?>
ga('ecommerce:addItem', {
'id': '<?php echo $transaction_id; ?>',
'name': '<?php echo $item->get_name(); ?>',
'sku': '<?php echo $product->get_sku(); ?>',
'category': '<?php echo $category; ?>',
'price': '<?php echo wc_get_price_excluding_tax($product); // OR wc_get_price_including_tax($product) ?>',
'quantity': '<?php echo $item->get_quantity(); ?>',
'currency': '<?php echo get_woocommerce_currency(); // Optional ?>'
});
<?php
endforeach; // LOOP END
?>
ga('ecommerce:send');
</script>
<?php
This code is partially tested and doesn't throw errors… But it need to be tested for real. I hope it will work.
Related:
Google Analytics related documentation (made from this documentation)
How to get WooCommerce order details
Get Order items and WC_Order_Item_Product in Woocommerce 3
I have a Woocommerce store and I like to send an order completion data to an affiliate and they ask me to include the following code:
<script>
lw("setCurrency", "numeric currency code, e.g. 978 for Euro");
lw("addItem", {
id: "ID (as given in the XML) of first product in order"
,price: "unit price of first product, without VAT e.g. 13,49"
,quantity: "quantity of first product"
,payout: "1"
});
lw("addItem", {
id: "ID (as given in the XML) of second product in order"
,price: "unit price of second product, without VAT e.g. 25,16"
,quantity: "quantity of second product"
,payout: "1"
});
// more items
lw("setCoupon", "0");
lw("thankyou", {
orderid: "unique order ID"
,status: "pending"
});
</script>
<noscript>
<img
src="//go.linkwi.se/delivery/acl.php?program=program_ID&decimal
=,_or_.&itemid[1]=ID_of_first_product&itemprice[1]=unit_pri
ce_of_first_product&itemquantity[1]=quantity_of_first_product&a
mp;itempayout[1]=1&itemid[2]=ID_of_second_product&itemprice
[2]=unit_price_of_second_product&itemquantity[2]=quantity_of_se
cond_product&itempayout[2]=1&coupon_price=0&status=pend
ing&orderid=unique_order_ID" style="width:0px;height:0px;"/>
</noscript>
In my thank you page - Checkout Page.
I have read that this is related to the WooCommerce Data Layer, I have searched for many hours not found anything to help me.
Thank you in advance.
Adding additional info
I use the Header and Footer plug in of WordPress and put the following code:
<!-- LinkWise Script -->
<script async src="//go.linkwi.se/delivery/js/tl.js"></script>
<script>
window.lw=window.lw||function(){(lw.q=lw.q||[]).push(arguments)};lw
.l=+new Date;
lw("setProgram", "12686");
lw("setDecimal", ",");
</script>
<!-- End LinkWise Script -->
on every page of the website on header
Here is a way to integrate it; But you will have to add some settings to the code:
The program number (your program affiliation ID)
The decimal separator (can be a coma or a point).
The currency number code (in ISO_4217 format).
You will have to remove other related code from header or footer as not needed anymore…
The code is divided in 2 parts:
The utility function that contain Linkwise Affiliate script (and settings)
The hooked function that will run Linkwise Affiliate scripts on order received (2 choices):
The first function (Where you will add your settings):
// Utility function that contain Linkwise Affiliate script
function linkwise_affiliate_scripts( $order_id ){
## --- YOUR SETTINGS START BELOW --- ##
$program_id = '12686'; // <== Your program number
$decimal_sep = ','; // Decimal separator
$currency = '978'; // For "EUR" => See: https://en.wikipedia.org/wiki/ISO_4217
## --- END SETTINGS --- ##
$order = wc_get_order( $order_id );
$order_status = $order->get_status();
$items_string = array();
$count = 0;
?>
<script async src="//go.linkwi.se/delivery/js/tl.js"></script>
<script>
window.lw=window.lw||function(){(lw.q=lw.q||[]).push(arguments)};
lw .l=+new Date;
lw("setProgram", "<?php echo $program_id; ?>");
lw("setDecimal", "<?php echo $decimal_sep; ?>");
</script>
<script>
lw("setCurrency", "<?php echo $currency; ?>"); // Set your currency
<?php
foreach( $order->get_items() as $item ):
$count++;
$item_id = $item->get_id(); // The item ID
// Get an instance of the WC_Product object
$product = $item->get_product();
$product_id = $item->get_product_id(); // Product ID
$price_excl_vat = wc_get_price_excluding_tax( $product ); // Unit price excluding VAT
$item_qty = $item->get_quantity(); // Item quantity
$payout = '1'; // (???)
// The string for the <noscript> at the bottom
$items_string[] = "itemid[$count]=$item_id&itemprice[$count]=$price_excl_vat&itemquantity[$count]=$item_qty&a
mp;itempayout[$count]=$payout";
?>
lw("addItem", {
id: "<?php echo $item_id; // Or can be the product ID (may be) ?>"
,price: "<?php echo $price_excl_vat; ?>"
,quantity: "<?php echo $item_qty; ?>"
,payout: "<?php echo $payout; ?>"
});
<?php
endforeach;
// Set the array of items strings in a unique string
$items_string = implode( '&', $items_string );
?>
// Other items types
<?php
$coupon_discounts = $coupon_discounts_tax = 0;
foreach( $order->get_items('coupon') as $item_coupon ){
$coupon_discounts += $item_coupon->get_discount();
$coupon_discounts_tax += $item_coupon->get_discount_tax();
}
?>
lw("setCoupon", "<?php echo $coupon_discounts; ?>");
lw("thankyou", {
orderid: "<?php echo $order_id; ?>"
,status: "<?php echo $order_status; ?>"
});
</script>
<noscript>
<img
src="//go.linkwi.se/delivery/acl.php?program=<?php echo $program_id; ?>&decimal=<?php echo $decimal_sep; ?>&<?php echo $items_string; ?>&coupon_price=<?php echo $coupon_discounts; ?>&status=<?php echo $order_status; ?>&orderid=<?php echo $order_id; ?>" style="width:0px;height:0px;"/>
</noscript>
<?php echo 'test';
}
And the hooked function that will run the utility function (with 2 different possibilities):
A) Using woocommerce_thankyou action hook:
add_action( 'woocommerce_thankyou','wc_linkwise_affiliate_thanyou_integration', 20, 1 );
function wc_linkwise_affiliate_thanyou_integration( $order_id ){
if ( empty($order_id) || $order_id == 0 )
return; // Exit
linkwise_affiliate_scripts( $order_id ); // Run the Linkwise Affiliate
}
B) or Using WordPress wp_footer action hook:
add_action( 'wp_footer', 'wc_linkwise_affiliate_order_received_integration' );
function wc_linkwise_affiliate_order_received_integration() {
if ( ! is_wc_endpoint_url( 'order-received' ) )
return; // Exit
global $wp;
$order_id = absint( $wp->query_vars['order-received'] );
if ( empty($order_id) || $order_id == 0 )
return; // Exit
linkwise_affiliate_scripts( $order_id ); // Run the Linkwise Affiliate
}
Code goes in function.php file of your active child theme (or theme).
Tested and works.
You can check in your browser console, you will see no errors and the correct output flags in Order received page.