Google analytics integration for a custom Order received page in Woocommerce 3

后端 未结 1 800
花落未央
花落未央 2021-01-22 04:33

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 analyti

相关标签:
1条回答
  • 2021-01-22 05:25

    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
    0 讨论(0)
提交回复
热议问题