Example Meta Pixel Implementation
The following is an example implementation that allows sending events through to Meta for reporting.
This script can be placed in your Wordpress theme's header.php file inside <script></script> tags.
You can edit this file by going to Appearance > Theme Editor > header.php.
It does not replace the Meta Pixel script which must also be included.
The code below is just an example. Events can be customised or added. See the Analytics section for more information on plugin events.
Example: Meta Pixel eCommerce Events
(function withwine_MetaPixel() {
'use strict';
const MAX_PRODUCTS = 200;
const CHECKOUT_REDIRECT_DELAY = 1000;
function isValidNumber(value) {
return typeof value === 'number' && Number.isFinite(value);
}
function isPositiveNumber(value) {
return isValidNumber(value) && value > 0;
}
function getProductId(product) {
return isPositiveNumber(product?.id)
? String(product.id)
: null;
}
function getProductUnitPrice(product) {
if (!isPositiveNumber(product?.minimumUnitPurchase)) {
return null;
}
const price =
product.calculatedUserPrice ?? product.minimumUnitPrice;
if (!isValidNumber(price) || price < 0) {
return null;
}
return price / product.minimumUnitPurchase;
}
/**
* Format a WithWine product for Meta Pixel.
*
* @param {Object} product
* @param {number} [quantity]
* @param {number} [itemTotal]
*/
function formatProduct(product, quantity, itemTotal) {
const result = {
id: getProductId(product),
name: product.name,
brand: product.brandNameOverride || undefined,
category: product.productType || undefined,
category2: product.productGroup || undefined,
category3: product.wineType || undefined,
category4: product.variety || undefined,
category5:
product.subRegion ||
product.region ||
product.state ||
undefined
};
const effectiveQuantity = quantity === undefined
? product.minimumUnitPurchase
: quantity;
if (isPositiveNumber(effectiveQuantity)) {
result.quantity = effectiveQuantity;
}
let unitPrice = null;
if (
isValidNumber(itemTotal) &&
itemTotal >= 0 &&
isPositiveNumber(effectiveQuantity)
) {
unitPrice = itemTotal / effectiveQuantity;
} else if (itemTotal === undefined) {
unitPrice = getProductUnitPrice(product);
}
if (isValidNumber(unitPrice)) {
result.price = unitPrice;
}
return result;
}
function track(eventName, payload, options) {
if (typeof window.fbq !== 'function') {
return;
}
if (options) {
window.fbq('track', eventName, payload, options);
} else {
window.fbq('track', eventName, payload);
}
}
function trackCustom(eventName, payload) {
if (typeof window.fbq === 'function') {
window.fbq('trackCustom', eventName, payload);
}
}
function getContentIds(contents) {
return contents.map(item => item.id);
}
function getValidCartItems(cart) {
if (!Array.isArray(cart)) {
return [];
}
return cart.filter(item =>
item?.product &&
getProductId(item.product) &&
isPositiveNumber(item.quantity)
);
}
// --------------------------------------------------
// Product views
// --------------------------------------------------
window.addEventListener('out:withwine:view_products', function(event) {
const data = event.detail?.v1;
if (!Array.isArray(data?.products) || !data.products.length) {
return;
}
const products = data.products
.filter(product => product && getProductId(product))
.slice(0, MAX_PRODUCTS);
if (!products.length) {
return;
}
const contents = products.map(product => formatProduct(product));
const componentType = data.component?.type?.toLowerCase() || '';
const isProductDetail = [
'product-details',
'product-view-event'
].includes(componentType);
if (isProductDetail) {
const product = products[0];
const value =
product.calculatedUserPrice ?? product.minimumUnitPrice;
const payload = {
content_type: 'product',
content_ids: [String(product.id)],
contents: [formatProduct(product)]
};
if (
product.paymentCurrency &&
isValidNumber(value) &&
value >= 0
) {
payload.currency = product.paymentCurrency;
payload.value = value;
}
track('ViewContent', payload);
} else {
const listId =
data.component?.data?.galistid ||
(
componentType +
(
data.component?.data?.productlist_id ||
data.component?.data?.productlist?.id ||
''
)
);
const listName =
data.component?.data?.galistname || listId;
trackCustom('ViewProductList', {
content_type: 'product',
content_ids: getContentIds(contents),
contents: contents,
list_id: listId,
list_name: listName
});
}
});
// --------------------------------------------------
// Add to cart
// --------------------------------------------------
window.addEventListener('out:withwine:add_to_cart', function(event) {
const data = event.detail?.v1;
if (!data?.added?.product || !data.cart) {
return;
}
const added = data.added;
const product = added.product;
if (!getProductId(product)) {
return;
}
const addedQuantity =
added.quantity - added.previousQuantity;
if (!isPositiveNumber(addedQuantity)) {
return;
}
const unitPrice = getProductUnitPrice(product);
const addedValue = unitPrice === null
? null
: unitPrice * addedQuantity;
const contents = [
formatProduct(product, addedQuantity, addedValue ?? undefined)
];
const payload = {
content_type: 'product',
content_ids: getContentIds(contents),
contents: contents
};
if (
product.paymentCurrency &&
isValidNumber(addedValue)
) {
payload.currency = product.paymentCurrency;
payload.value = addedValue;
}
track('AddToCart', payload);
});
// --------------------------------------------------
// Remove from cart
// --------------------------------------------------
window.addEventListener('out:withwine:remove_from_cart', function(event) {
const data = event.detail?.v1;
if (!data?.removed?.product || !data.cart) {
return;
}
const removed = data.removed;
const product = removed.product;
if (!getProductId(product)) {
return;
}
const removedQuantity =
removed.previousQuantity - removed.quantity;
if (!isPositiveNumber(removedQuantity)) {
return;
}
const unitPrice = getProductUnitPrice(product);
const removedValue = unitPrice === null
? null
: unitPrice * removedQuantity;
const contents = [
formatProduct(product, removedQuantity, removedValue ?? undefined)
];
const payload = {
content_type: 'product',
content_ids: getContentIds(contents),
contents: contents
};
if (
product.paymentCurrency &&
isValidNumber(removedValue)
) {
payload.currency = product.paymentCurrency;
payload.value = removedValue;
}
trackCustom('RemoveFromCart', payload);
});
// --------------------------------------------------
// Begin checkout
// --------------------------------------------------
window.addEventListener('out:withwine:begin_checkout', function(event) {
const data = event.detail?.v1;
const cartItems = getValidCartItems(data?.cart);
if (!cartItems.length) {
return;
}
if (typeof data.url !== 'string' || !data.url.trim()) {
return;
}
let checkoutUrl;
try {
checkoutUrl = new URL(data.url, location.href);
if (!['http:', 'https:'].includes(checkoutUrl.protocol)) {
return;
}
} catch {
return;
}
const contents = cartItems.map(item =>
formatProduct(
item.product,
item.quantity,
item.total
)
);
const payload = {
content_type: 'product',
content_ids: getContentIds(contents),
contents: contents
};
const currency = cartItems[0].product.paymentCurrency;
if (currency && isValidNumber(data.total)) {
payload.currency = currency;
payload.value = data.total;
}
if (isValidNumber(data.shipping)) {
payload.shipping = data.shipping;
}
if (isValidNumber(data.totalTaxAdded)) {
payload.tax = data.totalTaxAdded;
}
// Send the Meta Pixel event before navigation.
track('InitiateCheckout', payload);
// Cancel the original WithWine navigation if possible.
if (event.cancelable) {
event.preventDefault();
}
// Delay our redirect to allow the Pixel request
// time to be sent before leaving the page.
if (event.defaultPrevented) {
setTimeout(function() {
location.href = checkoutUrl.href;
}, CHECKOUT_REDIRECT_DELAY);
}
});
// --------------------------------------------------
// Checkout success
// --------------------------------------------------
window.addEventListener('out:withwine:checkout_success', function(event) {
const data = event.detail?.v1;
if (!data) {
return;
}
// -----------------------------------------------
// Completed order
// -----------------------------------------------
if (data.eventType === 'Order') {
if (!Array.isArray(data.orderItems)) {
return;
}
if (!isValidNumber(data.orderTotal)) {
return;
}
const orderItems = data.orderItems.filter(item =>
item &&
item.productId > 0 &&
isPositiveNumber(item.quantity)
);
const contents = orderItems.map(item => {
if (item.product) {
return formatProduct(
item.product,
item.quantity,
item.orderItemTotal
);
}
const result = {
id: String(item.productId),
name: 'Product #' + item.productId,
quantity: item.quantity
};
if (
isValidNumber(item.orderItemTotal) &&
item.orderItemTotal >= 0
) {
result.price = item.orderItemTotal / item.quantity;
}
return result;
});
const validContents = contents.filter(item => item.id);
const payload = {
currency: data.paymentCurrency || 'AUD',
value: data.orderTotal,
content_type: 'product',
content_ids: getContentIds(validContents),
contents: validContents
};
if (isValidNumber(data.totalTaxAdded)) {
payload.tax = data.totalTaxAdded;
}
if (isValidNumber(data.shipping)) {
payload.shipping = data.shipping;
}
// Use the actual WithWine order number,
// consistent with the GA4 transaction_id.
const orderNumber = data.orderNumber;
if (
orderNumber != null &&
String(orderNumber).trim()
) {
track('Purchase', payload, {
eventID: 'withwine_order_' + String(orderNumber)
});
} else {
track('Purchase', payload);
}
// -----------------------------------------------
// Join or update wine club
// -----------------------------------------------
} else if (data.eventType === 'JoinClub') {
const clubMemberId = data.clubMemberId;
if (
clubMemberId == null ||
!String(clubMemberId).trim()
) {
return;
}
const storageKey =
'withwine_meta_joinclub_' + String(clubMemberId);
// Match GA4: prevent duplicate new club
// registrations within the same session.
if (!data.isUpdate) {
try {
if (sessionStorage.getItem(storageKey)) {
return;
}
} catch {
// Storage may be unavailable; continue tracking.
}
}
const clubPayload = {};
if (data.clubId != null) {
clubPayload.club_id = String(data.clubId);
}
if (data.chargeInterval) {
clubPayload.charge_interval = data.chargeInterval;
}
if (data.bottleQuantity) {
clubPayload.bottle_quantity = data.bottleQuantity;
}
trackCustom(
data.isUpdate ? 'UpdateClub' : 'JoinClub',
clubPayload
);
// Record new memberships only after attempting
// to send the tracking event.
if (
!data.isUpdate &&
typeof window.fbq === 'function'
) {
try {
sessionStorage.setItem(storageKey, '1');
} catch {
// Ignore unavailable session storage.
}
}
}
});
})();