Home / eCommerce / Meta Pixel – InitiateCheckout Event
Duplicate Snippet

Embed Snippet on Your Site

Meta Pixel – InitiateCheckout Event

Meta Pixel - InitiateCheckout Event

Code Preview
php
<?php
// Track InitiateCheckout event on checkout page
add_action( 'wp_footer', 'voelgoed_meta_pixel_initiate_checkout', 20 );
function voelgoed_meta_pixel_initiate_checkout() {
    // Safety: don’t run in admin or during AJAX calls
    if ( is_admin() || wp_doing_ajax() ) {
        return;
    }
    // Must be checkout page
    if ( ! function_exists( 'is_checkout' ) || ! is_checkout() ) {
        return;
    }
    // Don’t fire on thank you page
    if ( function_exists( 'is_order_received_page' ) && is_order_received_page() ) {
        return;
    }
    // Must have Woo + cart
    if ( ! function_exists( 'WC' ) || ! WC()->cart || WC()->cart->is_empty() ) {
        return;
    }
    $cart = WC()->cart;
    // Build content_ids (use variation_id when present)
    $content_ids = [];
    foreach ( $cart->get_cart() as $cart_item ) {
        $id = ! empty( $cart_item['variation_id'] ) ? (int) $cart_item['variation_id'] : (int) $cart_item['product_id'];
        if ( $id ) {
            $content_ids[] = (string) $id;
        }
    }
    $content_ids = array_values( array_unique( $content_ids ) );
    // Force numeric value for JS
    $value    = (float) $cart->get_total( 'edit' );
    $currency = function_exists( 'get_woocommerce_currency' ) ? get_woocommerce_currency() : 'ZAR';
    $num_items = (int) $cart->get_cart_contents_count();
    ?>
    <script>
    (function () {
        // Prevent "fbq is not defined" console errors
        if (typeof fbq !== 'function') return;
        fbq('track', 'InitiateCheckout', {
            content_ids: <?php echo wp_json_encode( $content_ids ); ?>,
            content_type: 'product',
            value: <?php echo wp_json_encode( $value ); ?>,
            currency: <?php echo wp_json_encode( $currency ); ?>,
            num_items: <?php echo (int) $num_items; ?>
        });
    })();
    </script>
    <?php
}

Comments

Add a Comment