I want to track the number of button clicks in my coupon website. The button values are retrieved from custom fields created using the ACF plugin. I have a custom field total_clicks
. Every time when someone clicks the button, I want the value of total_clicks
to get updated.
How can I implement this with ACF and javascript?
I want to track the number of button clicks in my coupon website. The button values are retrieved from custom fields created using the ACF plugin. I have a custom field total_clicks
. Every time when someone clicks the button, I want the value of total_clicks
to get updated.
How can I implement this with ACF and javascript?
I'm not sure if the ACF Javascript API is available by default, or if you have to install it previously, and since I can't use it on here, this will pretty much be pseudo code for you to try, but try this:
In whatever page's JS area, you can add a document ready state to make sure the page has loaded, and listen for clicks.
document.addEventListener("DOMContentLoaded", function() {
var coupons = document.querySelectorAll(".class-name-of-coupon");
Object.values(coupons).forEach( (el) =>
{
el.addEventListener("click", function()
{
if ( acf.has("total_clicks") );
{
var prevClicks = acf.get("total_clicks");
acf.set("total_clicks", prevClicks++);
}
}
});
});
This will take every coupon with the class "class-name-of-coupon" and put a click listener on it that increments the field total_clicks
(if it exists) via the ACF API. I can't tell if you have access to the API, or how one would enable it, but that is the code that you would use.
Let me know how it goes!