A common task for ecommerce sites is needing to add a tracking pixel to the Order Completed, or Thank You page of WooCommerce. This pixel will help report data to an external service like Facebook Ads, Google Ads, Pinterest, or a CRM.
In today’s article I’ll share why the practice of adding code to a template is an issue and how to fix it.
- What is Thank You page code
- Why adding code to the thank you template is a potential issue
- Two alternatives to adding code directly to Thank You page template
What is Thank You page code?
Why adding code to the thank you template is a potential issue
To add this code you might open up your text editor and add the pixel code directly to the thankyou.php file in the WooCommerce plugin template directly. The first issue with this is that when the WooCommerce plugin is updated the modification will be overwritten and data reporting will go away unless it is re-applied. That’s why this is not a best practice.
What you want to happen is for the pixel to run after the customer completes the order, but code placed in a template file will execute each time this happens:
- The customer refreshes the order complete page then the WooCommerce Thank You pixel is fired again
- The customer shares the page URL with someone to see instructions on the page
- Customer leaves the “Thank You” page open in their browser for a few days and then refreshes
Each of these refreshes will register as a new sale causing reported order data to be a multiple of reality.
Two alternatives to adding code to Thank You page template
The woocommerce_thankyou hook is your friend
In the WooCommerce Thank You page template there is a woocommerce_thankyou hook added that will fire and send the Order ID as a parameter. Below is what the action looks like and as of WooCommerce 5.3.0:
do_action( 'woocommerce_thankyou', $order->get_id() );
The Order ID can be used to get order data to add to the javacript. We’ll also add a check to the database to keep this from running more than once.
One issue with the above script is it adds a postmeta table row per order. If your store has large numbers of orders you will want to remove postmeta rows that are not needed to reduce the overall size of the database. Removing unused postmeta rows is beyond the scope of this article.
First, copy the thank you page template to your site’s theme directory. Example, copy this file:
to this location:
Be sure to replace
[THEME_NAME] with the name of the active theme.
Inside the theme’s copy of the
Note: this code does not require copying the template. The
woocommerce_thankyou hook can be used to add the code to the order complete page.
I’ve shown two alternatives to data reporting issues that can arise when adding a WooCommerce Thank You pixel. Hopefully this is helpful to keep your reporting data clean and accurate and will keep your marketing team happy.
If you have any questions post them below or hit up Grow Development on Twitter!