Custom tracking code for the thanks page (woo themes, Woo Commerce ) snippets

/**
 * Add Tracking Code to the Order Recieved Page
 */
function wc_ninja_checkout_analytics($order_id) {
    $order = new WC_Order($order_id);
    $order_no = $order->get_order_number();
    $grand_total = $order->calculate_totals();
    $shipping_total = $order->calculate_shipping();
    $tax_total = $order->calculate_taxes();
    $currency = $order->get_order_currency();
    $items = $order->get_items();
?>

    <!-- Paste Tracking Code Under Here -->
    <script>
        ga('require', 'ecommerce', 'ecommerce.js');

        ga('ecommerce:addTransaction', {
            'id': '<?php echo $order_no; ?>', // Transaction ID
            'affiliation': '', // Affiliation or store name
            'revenue': '<?php echo $grand_total; ?>', // Grand Total
            'shipping': '<?php echo $shipping_total; ?>', // Shipping cost
            'tax': '<?php echo $tax_total; ?>', // Tax.
            'currency': '<?php echo $currency; ?>' // Local currency code.
        });
    </script>  
    <!-- End Tracking Code -->

    <?php
    // Output the loop
    foreach ($order->get_items() as $item) {
        // Getting some information
        $product = new WC_Product($item['product_id']);
        ?>  
        <!-- Paste Tracking Code Under Here -->
        <script>
            ga('ecommerce:addItem', {
                'id': '<?php echo $order_no; ?>', // Transaction ID.
                'name': '<?php echo $item['name']; ?>', // Product name.
                'sku': '<?php echo $product->get_sku(); ?>', // SKU/code.
                'category': '<?php echo $item['variation_id']; ?>', // Category or variation.
                'price': '<?php echo $item['line_total']; ?>', // Unit price.
                'quantity': '<?php echo $item['qty']; ?>', // Quantity.
                'currency': '<?php echo $currency; ?>'   // Local currency code.
            });
            ga('ecommerce:send');
        </script>  
        <!-- End Tracking Code -->

<?php }  }
add_action('woocommerce_thankyou', 'wc_ninja_checkout_analytics');

No comments:

Post a Comment