Adding standard Baidu Analytics tracking to WooCommerce is straightforward—simply insert the Baidu JS snippet before the closing </head> tag. Many themes and plugins even offer dedicated settings in the backend where you can paste your tracking ID, making the process even simpler.
However, implementing Baidu’s e-commerce analysis functionality requires a bit more technical effort. You’ll need to extract specific order data from WooCommerce and pass it to the Baidu Analytics script using their required format.
According to Baidu Analytics documentation, the e-commerce tracking code must be added to the order completion (thank you) page, immediately following the standard Baidu asynchronous JS code. This tracking code needs to capture various order details such as SKU IDs, product categories, prices, and quantities. We can achieve this by retrieving the data from the WooCommerce order object and injecting it into the Baidu JS snippet.
Retrieving Order Data for Baidu Analytics
The following PHP code snippet extracts the necessary order information. Since this code will be executed on the WooCommerce order completion page, we can directly access the $order_id variable.
$order = wc_get_order($order_id);
$items = $order->get_items();
$product_js = [];
foreach ($items as $item_id => $item_data) {
$_product = wc_get_product($item_data->get_data()[ 'product_id' ]);
$pro_cat_array = wp_get_post_terms($_product->ID, 'product_cat');
$sku = $_product->get_sku();
$qty = $item_data->get_quantity();
$pro_cat = implode(',', $pro_cat_array);
$product_name = $_product->get_name();
// Use the line item total
$pro_price = $item_data->get_data()[ 'total' ];
$product_js[] = [
'skuId' => $sku,
'category' => $pro_cat,
'skuName' => $product_name,
'Price' => $pro_price,
'Quantity' => $qty,
];
}
Injecting Order Data into Baidu Tracking Code
Once you have retrieved the order data, you can push it to the Baidu Analytics _hmt array using the _trackOrder command. Here is the JavaScript snippet with the PHP data injected:
<script>
_hmt.push([
'_trackOrder', {
'orderId' : '<?= $order_id; ?>',
'orderTotal': '<?= $order->get_total(); ?>',
'item' : <?= json_encode($product_js); ?>,
},
]);
</script>
To finalize the implementation, you can wrap this logic in a function and hook it into the woocommerce_thankyou action. This ensures the tracking code is dynamically generated and executed whenever a customer successfully completes an order.
