Meta Pixel Purchase Event for WooCommerce
Fires the Meta (Facebook) Pixel "Purchase" event with the order value, currency and product IDs on the order received page, once per order.
Opens WPIDE on
Code
add_action( 'woocommerce_thankyou', function ( $order_id ) {
$order = wc_get_order( $order_id );
if ( ! $order || $order->get_meta( '_wpide_meta_purchase_sent' ) ) {
return;
}
$ids = array();
foreach ( $order->get_items() as $item ) {
$ids[] = (string) ( $item->get_variation_id() ? $item->get_variation_id() : $item->get_product_id() );
}
$data = array(
'value' => round( (float) $order->get_total(), 2 ),
'currency' => $order->get_currency(),
'content_ids' => $ids,
'content_type' => 'product',
'num_items' => (int) $order->get_item_count(),
);
printf(
"<script>if (typeof fbq === 'function') { fbq('track', 'Purchase', %s, { eventID: %s }); }</script>\n",
wp_json_encode( $data ),
wp_json_encode( 'order-' . $order->get_order_key() )
);
$order->update_meta_data( '_wpide_meta_purchase_sent', time() );
$order->save();
}, 20 );
Notes
Needs the Meta Pixel base code on the page. The order key is sent as event ID so you can deduplicate with the Conversions API.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.