How to use ACF with javascript to update custom field values?

Question

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!

0
Q Studio 12 months 2020-04-27T07:32:06-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse