How to get order details for a Javascript tracking script? - javascript

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

Related

How to add Google Ads conversion purchase event to my WooCommerce Thank you Page

I saw this
Adding Google Ads Event Snippet To Conversion Page (thank you.php)
But I have a different situation. I am using " Auto Complete Processing WooCommerce orders on Thank you Page" and "Redirect WooCommerce checkout page" all these are inside my functions.php file.
This is what my functions.php file looks like. I hid my site with " ********* "
//Auto Complete Processing WooCommerce orders on Thankyou Page
add_action( 'woocommerce_thankyou', 'custom_woocommerce_auto_complete_order' );
function custom_woocommerce_auto_complete_order( $order_id ) {
if ( ! $order_id ) {
return;
}
$order = wc_get_order( $order_id );
if ( $order->has_status('processing') ) {
$order->update_status( 'completed' );
}
}
// Redirect WooCommerce checkout page to ******************** after the payament
add_action( 'woocommerce_thankyou', 'pfwp_redirect_woo_checkout');
function pfwp_redirect_woo_checkout( $order_id ){
$order = wc_get_order( $order_id );
$url = 'https://*********/*********/*********/';
if ( ! $order->has_status( 'failed' ) ) {
wp_safe_redirect( $url );
exit;
}
}
And I want to add the Event snippet inside the Thank You for google ads.
<!-- Event snippet for Purchase conversion page -->
<script>
gtag('event', 'conversion', {
'send_to': 'AW-***********/********kDENy8vL4o',
'value': 1.0,
'currency': 'SAR',
'transaction_id': ''
});
</script>
<!-- End Event snippet for Purchase conversion page -->
Because I am redirecting the thank you page to another page, the script will trigger? Or not?
And how and where do I add the Event snippet at the functions.php because I have a lot of code that control WooCommerce?
Since you're redirecting to another page, you have to add the conversion code on that page. To do that, I set a transient to pass that value.
Your functions for thank_you can be combined.
This is tested and should work for you.
add_action( 'woocommerce_thankyou', 'custom_woocommerce_auto_complete_order' );
function custom_woocommerce_auto_complete_order( $order_id ) {
if ( ! $order_id ) {
return;
}
$order = wc_get_order( $order_id );
if ( $order->has_status( 'processing' ) ) {
$order->update_status( 'completed' );
}
$url = 'https://*******/'; // Your redirect URL.
if ( ! $order->has_status( 'failed' ) ) {
ob_start();
set_transient( 'wc_order_total_for_google', $order->get_total( 'edit' ), 1 * MINUTE_IN_SECONDS );
wp_safe_redirect( $url );
exit;
}
}
add_action( 'wp_print_footer_scripts', 'dd_add_conversion_code' );
function dd_add_conversion_code() {
if ( is_page( your_custom_page_id ) ) { //Set your custom page ID here.
if ( false !== get_transient( 'wc_order_total_for_google' ) ) {
$order_total = get_transient( 'wc_order_total_for_google' );
?>
<!-- Event snippet for Purchase conversion page -->
<script>
gtag('event', 'conversion', {
'send_to': 'AW-***********/********kDENy8vL4o',
'value': <?php echo esc_attr( $order_total ); ?>,
'currency': 'SAR',
'transaction_id': ''
});
</script>
<!-- End Event snippet for Purchase conversion page -->
<?php
delete_transient( 'wc_order_total_for_google' );
}
}
}
If you add your script with the other tutorial:
add_action( 'woocommerce_thankyou', 'ds_checkout_analytics' );
And your redirection with:
add_action( 'woocommerce_thankyou', 'pfwp_redirect_woo_checkout');
Simply do this to make the tracking trigger before the redirection:
add_action( 'woocommerce_thankyou', 'pfwp_redirect_woo_checkout', 12 );
add_action( 'woocommerce_thankyou', 'ds_checkout_analytics', 11 );
By specifying the hook "priority", we've just told WordPress to run ds_checkout_analytics() before pfwp_redirect_woo_checkout(). Default priority is = 10

Loading twice WooCommerce thankyou page would duplicate Conversion tracking?

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.

Insert javascript code into the head tags of the woocommerce thank you page

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.

Linkwise Affiliate integration in Woocommerce thankyou page

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.

WordPress - Modify admin-header.php or use functions.php for inserting a jQuery script to header?

Im developing a Form with a (jQuery) onClick button so I can import results from other documents straight into WP Custom Fields.
To do this I MUST include this script to my Form:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
If I don't include this script then my Form wont work :(
And if I include this script then I can ADD NEW POST and use my Form + Button but then the EDIT POST page wont show up and I only see a WHITE SCREEN.
Finally I figured out if I insert this CODE to LINE 59 in admin-header.php:
<?php if ( is_admin() && $parent_file == 'edit.php') { ?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<?php } ?>
Then everything will work 100% as I want :D
I thought WP already was using/including this script by default but this is NOT true as I can see. At least not for WP-Backend (Post page).
The problem is: I dont want to edit WP CORE files, so my question is how can I get the same result using functions.php instead of editing admin-header.php?
Just to show you how admin-header looks like from LINE 50 to LINE 73:
<title><?php echo $admin_title; ?></title>
<?php
wp_enqueue_style( 'colors' );
wp_enqueue_style( 'ie' );
wp_enqueue_script('utils');
$admin_body_class = preg_replace('/[^a-z0-9_-]+/i', '-', $hook_suffix);
?>
<?php if ( is_admin() && $parent_file == 'edit.php') { ?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<?php } ?>
<script type="text/javascript">
addLoadEvent = function(func){if(typeof jQuery!="undefined")jQuery(document).ready(func);else if(typeof wpOnload!='function'){wpOnload=func;}else{var oldonload=wpOnload;wpOnload=function(){oldonload();func();}}};
var ajaxurl = '<?php echo admin_url( 'admin-ajax.php', 'relative' ); ?>',
pagenow = '<?php echo $current_screen->id; ?>',
typenow = '<?php echo $current_screen->post_type; ?>',
adminpage = '<?php echo $admin_body_class; ?>',
thousandsSeparator = '<?php echo addslashes( $wp_locale->number_format['thousands_sep'] ); ?>',
decimalPoint = '<?php echo addslashes( $wp_locale->number_format['decimal_point'] ); ?>',
isRtl = <?php echo (int) is_rtl(); ?>;
</script>
As you can se my CODE is on LINE 11,12 and 13 to make it work.
You can try something like this in your theme functions.php
function admin_add_script() {
wp_enqueue_script('jquery_script', 'http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js', array(), null);
}
add_action('admin_head-edit.php', 'admin_add_script');
Try adding this to your functions.php:
<?php
function add_jquery_data() {
global $parent_file;
if ( isset( $_GET['action'] ) && $_GET['action'] == 'edit' && isset( $_GET['post'] ) && $parent_file == 'edit.php') {
echo "<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>";
}
}
add_filter('admin_head', 'add_jquery_data');
?>
I hope this helps.

Categories