Skip to content

Instantly share code, notes, and snippets.

@JohannMG
Last active May 19, 2019 15:58
Show Gist options
  • Save JohannMG/6478f6664930e2309ca0 to your computer and use it in GitHub Desktop.
Save JohannMG/6478f6664930e2309ca0 to your computer and use it in GitHub Desktop.
Quick JS for FB conversion Pixel. No duplicate conversion pixel firing.
/*
fires on checkout THANK YOU page on a successful transaction
behavior:
checks if facebook tracking pixel is initiliazed
if not: waits 200ms
then, calls facebook FBQ
get data via:
transactionfield: {total: 156.69, ordernum: "22"}
These global values set by JS in the PHP Script on woocommerce thankyou page
*/
(function() {
//if the object exists, then check it has not already been sent to FB
if (typeof localStorage['wcaquastore'] !== 'undefined') {
try {
var existing = JSON.parse(localStorage['wcaquastore']);
if (existing.indexOf(String(transactionfield.ordernum)) > 0) {
return;
}
} catch (err) {
localStorage['wcaquastore'] = JSON.stringify([0]);
}
}
//if FB object not setup yet, wait 250ms
if (typeof fbq == 'undefined') {
setTimeout(sendToFB, 250);
} else sendToFB();
function sendToFB() {
//last check for FB object
if (typeof fbq != 'undefined') {
fbq('track', 'Purchase', {
value: String(transactionfield.total),
currency: 'CAD'
});
console.log('sent');
//add order number to localstorage incase the conf page is reloaded
if (typeof localStorage['wcaquastore'] === 'undefined') {
localStorage['wcaquastore'] = JSON.stringify([transactionfield.ordernum]);
} else {
var existing = JSON.parse(localStorage['wcaquastore']);
existing.push(transactionfield.ordernum);
localStorage['wcaquastore'] = JSON.stringify(existing);
}
}
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment