Use CMB2 to add a custom metabox to add tracking information to WooCommerce orders. The information is then added to the "Completed Order" email.
Elizabeth commented on my Add info to WooCommerce order emails post asking if I knew a way to put tracking information into the order complete email. As shown in the original post, adding content to emails is easy – as long as you have the data to add.
I quickly put together a plugin that uses CMB2 to add a metabox where the tracking number and tracking url can be added to an order.
The CMB2 fields are very simple – a ‘text‘ field for the tracking number (which will likely be alphanumeric) and ‘text_url‘ field for the tracking url.
The ‘object_type‘ (aka post type) for the WooCommerce Order page is ‘shop_order.’
CMB2 is optional here as you can manually add ‘tracking_number‘ and ‘tracking_url‘ custom fields to the order. In fact, when you add them via the metabox fields you will see them listed in the Custom Fields section! CMB2 primarily makes for a nice interface.
The email code looks longer than you might think – that’s because of error checking (that the order has the tracking number and url) and slightly different text for plain text and html emails.
You can see that it only runs for the ‘customer_completed_order‘ email.
The shipping provider is not stored in the order’s post meta but is determined by examining the tracking url. This is probably quite reliable.
Custom REST API endpoint
I wrote additional code for this small project but have purposely omitted it from this post because it was a paid project and it would be unfair to make that code available for free. The code was a custom REST API endpoint that allowed a third party service push a tracking number and url to the website. The endpoint stored the number and url in the post meta and the code above uses that in the order email.
Supporting ‘Email Template Customizer for WooCommerce’ plugin
I got an email reporting that my code did not work when the Email Template Customizer for WooCommerce plugin was in use. I found that that plugin does not call the ‘woocommerce_email_order_details‘ hook. My solution is to use a hook that the plugin does support – ‘woocommerce_email_after_order_table‘. This solution requires the website owner to add a ‘WC Hook’ field to the ‘Completed Order’ email and to choose the ‘woocommerce_email_after_order_table‘ action.
Here are screenshots of the changes to make to the email. Click to see the full size image.