- Make sure you have the Facebook Pixel installed on your website and that it is properly configured.
- Add the following code to your theme’s functions.php file or a custom plugin:
add_action( ‘woocommerce_thankyou’, ‘facebook_purchase_event’ );
function facebook_purchase_event( $order_id ) {
if ( ! $order_id ) {
return;
}
// Get the order object
$order = wc_get_order( $order_id );
$total = $order->get_total();
$currency = $order->get_currency();
$content_ids = array();
$content_type = ‘product’;
// Loop through order items
foreach ( $order->get_items() as $item ) {
$product = $item->get_product();
$content_ids[] = $product->get_id();
}
// Prepare the event data
$event_data = array(
‘value’ => $total,
‘currency’ => $currency,
‘content_ids’ => implode( ‘,’, $content_ids ),
‘content_type’ => $content_type,
);
// Trigger the “Purchase” event
?>
<script>
fbq(‘track’, ‘Purchase’, <?php echo json_encode( $event_data ); ?>);
</script>
<?php
}
This code will trigger the “Purchase” event on the Facebook Pixel when a customer is directed to the thank you page after completing a purchase. It will also include the purchase value, currency, and the product IDs in the event data.