If you integrate any third-party services with your WooCommerce site (for ads, analytics, marketing, drop shipping, or A/B testing), it’s often helpful or necessary to provide conversion data through javascript.
A lot of the big services, like Google Analytics (tutorial) or Facebook ads, have off-the-shelf extensions you can use. But for smaller services, you often have to write some custom code to send them the conversion information.
Generally the easiest way to do this is by using the woocommerce_thankyou hook. This action is only fired on the order confirmation page and also provides the $order_id variable, which gives access to all the order details.
Using the Hook
Basic Conversion Information
Here’s an example of how you might pass data like order id, order total, and customer e-mail to a third-party service using the woocommerce_thankyou hook:
https://gist.github.com/devinsays/3d8ccc69a1f433bc6f88
Product Conversion Information
Occasionally you might also want to send specific information about which products were purchased. That information is also available. If you’re outputting it into a javascript variable, it might look something like this:
https://gist.github.com/devinsays/d65db56ad333782e9424
Additional Information
Depending on the service you’re integrating with, you may also need to send address information, tax amounts, or coupon information. You can always look through the WooCommerce docs to figure out how to get this. A var_dump of $order can also be really helpful when looking for specific pieces of data.
Alternates to the Hook
I recently had a project where the conversion data needed to be output in the footer markup (using the wp_footer hook) rather than inline after the order markup, which is where the woocommerce_thankyou hook places it.
This was a bit tricker to implement since I didn’t have immediate access to the $order_id variable in wp_footer. I also now needed to add some conditional logic in order to display the script only on the thankyou page.
But, after a bit of digging I found a solution. To output the script only on the order confirmation page, I used the WooCommerce function is_order_received_page. And to get access to the order information, I used $wp->query_vars[‘order-received’].
Here’s what an example of this method looks like:
https://gist.github.com/devinsays/dfdddebda9d3108c0ba1
