Skip to content

Instantly share code, notes, and snippets.

@woogists
Last active March 10, 2023 16:31
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save woogists/955db81b57a5bf6f7d88fefffef2fa85 to your computer and use it in GitHub Desktop.
Save woogists/955db81b57a5bf6f7d88fefffef2fa85 to your computer and use it in GitHub Desktop.
[Frontend Snippets] Custom tracking code for the thanks page
/**
* Add custom tracking code to the thank-you page
*/
add_action( 'woocommerce_thankyou', 'my_custom_tracking' );
function my_custom_tracking( $order_id ) {
// Lets grab the order
$order = wc_get_order( $order_id );
/**
* Put your tracking code here
* You can get the order total etc e.g. $order->get_total();
*/
// This is the order total
$order->get_total();
// This is how to grab line items from the order
$line_items = $order->get_items();
// This loops over line items
foreach ( $line_items as $item ) {
// This will be a product
$product = $order->get_product_from_item( $item );
// This is the products SKU
$sku = $product->get_sku();
// This is the qty purchased
$qty = $item['qty'];
// Line item total cost including taxes and rounded
$total = $order->get_line_total( $item, true, true );
// Line item subtotal (before discounts)
$subtotal = $order->get_line_subtotal( $item, true, true );
}
}
@nilsbosman
Copy link

@tarsonis123 Hi, for sure.
You can find the documentation for adding meta data to orders in WooCommerce here. The first time you visit the thank-you page it wil check if the meta data exists, it doens't since it's the first time it's been openend. It will run the tracking code part and add the meta data. The second time you visit the thank-you page it will check if the meta exists again. This time it does exists since it's already been visited and skips the tracking code part.

It uses the woocommerce_thankyou action that is part of the woocommerce thank-you page template, see here.

@pavr0m
Copy link

pavr0m commented May 12, 2022

Got deprecation warning here:
get_product_from_item is deprecated since version 4.4.0! Use $item->get_product() instead.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment