I have read quite a lot of possible ways to do it but after going through each of them I'm still not able to understand what should be the correct way of doing it and how the correct way works.
Question:
When the woo-commerce add to cart hook woocommerce_add_to_cart
is triggered I want to send the recently added product data (and also user data) from a javascript function to an analytics data collector tool (through analytics.io in this case).
Problem in implementation:
The hooks such as wp_head
wp_footer
are able to run javascript code inside of them either by wp_localize_script
or echo <script>//some js code</script>
. Whereas the woocommerce hooks such as woocommerce_add_to_cart
can't run javascript code inside them. As per my understanding this is due the fact that woocommerce_add_to_cart
update is happening via ajax.
What I've tried till now:
One possible solution I found was when the woocommerce_add_to_cart
hook is triggered change the data attribute of the Add to cart button and then read them in the jQuery script via added_to_cart
event. For reference, I implemented this: https://stackoverflow.com/questions/62780949/get-specific-woocommerce-product-data-on-added-to-cart-javascript-event and this works.
What I want:
I want to update/create a javascript object when the woocommerce hook is triggered and then send that data via a javascript function to the analytics tool. Is adding data attributes to the button/HTML element a good way to do this task?
P.S- I'm new to the WordPress/Php ecosystem and would really appreciate it if someone can explain a possible solution to my question in detail.