Home / eCommerce / Meta Pixel – AddToCart Event
Duplicate Snippet

Embed Snippet on Your Site

Meta Pixel – AddToCart Event

Meta Pixel - AddToCart Event

Code Preview
php
<?php
/**
 * =============================================================================
 * META PIXEL — AddToCart
 * =============================================================================
 * - Single product: fires on form submit (no jQuery required)
 * - Archives AJAX: listens to WooCommerce 'added_to_cart' (requires jQuery)
 * - Fallback: click listener on add_to_cart_button if jQuery missing
 */
add_action('wp_footer', 'voelgoed_meta_pixel_add_to_cart', 20);
function voelgoed_meta_pixel_add_to_cart() {
    if (!function_exists('is_woocommerce')) {
        // still allow single product if is_product exists
    }
    $is_single = (function_exists('is_product') && is_product());
    $is_archive = (
        function_exists('is_shop') && is_shop()
        || function_exists('is_product_category') && is_product_category()
        || function_exists('is_product_tag') && is_product_tag()
    );
    // Only output on Woo product contexts
    if (!$is_single && !$is_archive) {
        return;
    }
    $fallback_product_id = 0;
    $fallback_price      = 0.0;
    $currency            = function_exists('get_woocommerce_currency') ? get_woocommerce_currency() : 'ZAR';
    if ($is_single && function_exists('wc_get_product')) {
        $product = wc_get_product(get_the_ID());
        if ($product) {
            $fallback_product_id = (int) $product->get_id();
            $fallback_price      = (float) wc_get_price_to_display($product);
        }
    }
    ?>
    <script>
    (function () {
        if (typeof fbq !== 'function') return;
        var currency = <?php echo wp_json_encode($currency); ?>;
        var fallbackId = <?php echo (int) $fallback_product_id; ?>;
        var fallbackPrice = <?php echo wp_json_encode((float) $fallback_price); ?>;
        function parsePrice(text) {
            if (!text) return null;
            // Keep digits, dot, comma then normalize commas
            var cleaned = String(text).replace(/[^0-9.,]/g, '').replace(/,/g, '');
            var n = parseFloat(cleaned);
            return isFinite(n) ? n : null;
        }
        function sendAddToCart(productId, qty, price) {
            var payload = {
                content_ids: [String(productId)],
                content_type: 'product',
                currency: currency
            };
            if (qty && qty > 0) payload.num_items = qty;
            if (typeof price === 'number' && isFinite(price)) payload.value = price;
            fbq('track', 'AddToCart', payload);
        }
        // ---------------------------------------------------------------------
        // SINGLE PRODUCT: track add-to-cart form submit (no jQuery needed)
        // ---------------------------------------------------------------------
        if (document.body.classList.contains('single-product')) {
            document.addEventListener('submit', function (e) {
                var form = e.target;
                if (!form || !form.classList || !form.classList.contains('cart')) return;
                // Product ID: variation_id if selected, else fallback
                var variationInput = form.querySelector('input[name="variation_id"]');
                var productInput   = form.querySelector('input[name="add-to-cart"]');
                var productId = null;
                if (variationInput && variationInput.value && parseInt(variationInput.value, 10) > 0) {
                    productId = parseInt(variationInput.value, 10);
                } else if (productInput && productInput.value && parseInt(productInput.value, 10) > 0) {
                    productId = parseInt(productInput.value, 10);
                } else if (fallbackId > 0) {
                    productId = fallbackId;
                }
                var qtyInput = form.querySelector('input.qty');
                var qty = qtyInput && qtyInput.value ? parseInt(qtyInput.value, 10) : 1;
                if (!qty || qty < 1) qty = 1;
                // Try to read the current displayed price (helps variations)
                var price = null;
                var varPriceEl = document.querySelector('.woocommerce-variation-price .amount');
                if (varPriceEl) price = parsePrice(varPriceEl.textContent);
                if (price === null) {
                    var basePriceEl = document.querySelector('.summary .price .amount');
                    if (basePriceEl) price = parsePrice(basePriceEl.textContent);
                }
                if (price === null && typeof fallbackPrice === 'number') price = fallbackPrice;
                if (productId) {
                    sendAddToCart(productId, qty, price);
                }
            }, true);
        }
        // ---------------------------------------------------------------------
        // ARCHIVES AJAX: WooCommerce triggers jQuery event "added_to_cart"
        // ---------------------------------------------------------------------
        if (typeof jQuery !== 'undefined') {
            jQuery(function ($) {
                $(document.body).on('added_to_cart', function (e, fragments, cart_hash, $button) {
                    if (!$button || !$button.length) return;
                    var productId = $button.data('variation_id') || $button.data('product_id');
                    var qty = 1;
                    // Try to infer quantity if present
                    var $qty = $button.closest('li.product, .product').find('input.qty');
                    if ($qty.length) {
                        var q = parseInt($qty.val(), 10);
                        if (q > 0) qty = q;
                    }
                    if (productId) {
                        // Price is usually not present on button data; omit value if unknown
                        sendAddToCart(parseInt(productId, 10), qty, null);
                    }
                });
            });
        } else {
            // Fallback: click listener (no AJAX confirmation, but better than nothing)
            document.addEventListener('click', function (e) {
                var btn = e.target && e.target.closest ? e.target.closest('a.add_to_cart_button') : null;
                if (!btn) return;
                var productId = btn.getAttribute('data-product_id');
                if (productId) {
                    sendAddToCart(parseInt(productId, 10), 1, null);
                }
            }, true);
        }
    })();
    </script>
    <?php
}

Comments

Add a Comment