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

admin2025-01-07  3

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?

Share Improve this question edited Feb 16, 2021 at 18:28 Q Studio 2,5267 gold badges25 silver badges39 bronze badges asked Apr 27, 2020 at 12:32 Nirmal KUmarNirmal KUmar 11 silver badge2 bronze badges 2
  • Js and php don't communicate in that way, but you could set up a custom php page that takes ajax, and post increments to the acf variable. – Joel Hager Commented Apr 27, 2020 at 12:52
  • Thanks for the info. I was coming across ACF javascript API. Will it able to accomplish what we expect? – Nirmal KUmar Commented Apr 27, 2020 at 17:01
Add a comment  | 

1 Answer 1

Reset to default 0

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!

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736257861a470.html

最新回复(0)