Hi Members,
I am looking for a solution here.
I have a woo-commerce website. I am looking to integrate webengage with it. I need to pass an event to webengage called "Added to cart" along with the product details that have been added to cart ( like product name, quantity, sku, sale price, reg price etc..)
My site is using Ajax and I am not sure how to fire script after product is added to cart via ajax along with the product data as mentioned above.
My site products are more of variation products, So I need to pass variation name aloing with the product title, price, sku, reg price, sale price, sku.
Any help is much appreciated. Thanks!
Naveen Chand answers:
WooCommerce offers a hook that fires when an item is added to the cart. It is: woocommerce_add_to_cart
This hook provides the following variables:
$cart_item_key,
$product_id,
$quantity,
$variation_id,
$variation,
$cart_item_data
So you can use them in your custom function.
To send data to any API from this function, you can use wp_remote_post or wp_remote_get methods.
Here is a sample code that sends data after product is added to the cart:
function action_woocommerce_add_to_cart( $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data ) {
//your code here
//sample code...
$data = array( 'key1' => 'value1', 'key2' => 'value2' );
$response = wp_remote_post( 'http://httpbin.org/post', array( 'data' => $data ) );
}
add_action( 'woocommerce_add_to_cart', 'action_woocommerce_add_to_cart', 10, 6 );
Hope you will find this useful to send your data to WebEngage API.
Jayaram Y comments:
Hi Naveen,
Can you give me a rough sample code.
Below is the event that needs to trigger to webengage.
<script>
webengage.track("Added To Cart", {
"Product ID" : <?php echo $product_id; ?>,
"Price" : <?php echo $price; ?>,
"Quantity" : <?php echo $quantity; ?>,
"SKU Code": "<?php echo $sku; ?>",
"Product Name" : "<?php echo $product_name; ?>",
"Currency" : "INR",
});
</script>
here product name will include the variation name as well.. say variations are for 1 month, 2 months, 3 months, and user has choose product 2 months, then the product name will be "productxyz - 2 months" and its SKU code should come i.e PXYZ2 etc..
Jayaram Y comments:
Or Instead if triggering / running script, I need to call curl as they mentioned in this URL - https://docs.webengage.com/docs/rest-api-tracking-events
Naveen Chand comments:
Hi Jayaram,
I have quickly gone through the API docs of WebEngage. Here is the sample code but please tweak it around to get desired result:
function action_woocommerce_add_to_cart( $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data ) {
$webengage_action = "Added To Cart";
$cartitems = WC()->cart->get_cart();
$cart_item = $cartitems[$cart_item_key];
$product = $cart_item['data'];
$product_name = $product->get_name();
$product_sku = $product->get_sku();
$product_id = $cart_item['product_id'];
$quantity = $cart_item['quantity'];
$price = WC()->cart->get_product_price( $product );
$subtotal = WC()->cart->get_product_subtotal( $product, $cart_item['quantity'] );
$get_variation = wc_get_product($variation_id);
$variation_name = $variation->get_formatted_name();
$event_data = array {
'product_id' => $product_id,
'price' => $price,
'quantity' => $quantity,
'sku_code' => $product_sku,
'product_name' => $variation_name
'currency' => 'INR',
}
$data = array(
'userId' => get_current_user_id(),
'eventName' => $webengage_action,
'eventTime' => current_time('Y-m-d'),
'eventData' => $event_data
)
$webengage_API = "PUT_API_HERE";
$webengage_url = "https://api.webengage.com/v1/accounts/" .$webengage_API ."/events";
$response = wp_remote_post( $webengage_url, array( 'data' => $data ) );
}
add_action( 'woocommerce_add_to_cart', 'action_woocommerce_add_to_cart', 10, 6 );
Jayaram Y comments:
Hi Naveen,
For the API call, userID or anonymousId is mandatory which we don't have if user is not logged in.
Webengage, automatically creates anonymousId for all visitors which we can't fetch as its automatically done at their end and from same user if we pass user id after getting user details, then it converts that to known user.
So my question here is, can we run script when ajax add to cart event is fired along with the attributes?
When i tried your code and triggered script, it works but it comes on top of <html> tag and doesn't get executed. See attached screenshot.
Is there a way to get this script executed when user does add to cart?
Jayaram Y comments:
here is the image link in case you can't see it - https://ibb.co/m87d1W8
Naveen Chand comments:
I am not able to view the image. The site does not load for me. Could you copy paste the response or send it through some other source?
Have you checked in your WebEngage account if the data has been posted? If not, please check there once after adding to cart.
And also, let me know what message you are getting (above the <html>) on clicking add to cart button?
Jayaram Y comments:
Hi Naveen,
Yes, I tried your code and also tried the curl that webengage has given.
If we are pushing with API, userId or anonymousId is mandatory which we can't add here in my case. So running a script event push is the only option for me. If i add script in the function you given, its rendering above <html> tag in the response, so it's not getting executed.
Here is the drive link for screenshot - https://drive.google.com/file/d/1pNAfmOAjNKcTqgvKTIQ_UxZHGe8eLk-v/view?usp=sharing
Naveen Chand comments:
You can try adding these two in functions.php file of your theme.
The idea is to trigger your javascript script on wp_footer action hook using "added_to_cart" trigger event provided by woocommerce.
// Add some product data to "add to cart" button for 'added_to_cart' js event
//This code needs to be in functions.php
add_action( 'woocommerce_loop_add_to_cart_link', 'filter_wc_loop_add_to_cart_link', 10, 3 );
function filter_wc_loop_add_to_cart_link( $button_html, $product, $args ) {
if( $product->supports( 'ajax_add_to_cart' ) ) {
$search_string = 'data-product_sku';
// Insert custom product data as data tags
$replace_string = sprintf(
'data-product_name="%s" data-product_price="%s" data-currency="%s" %s',
$product->get_name(), // product name
wc_get_price_to_display( $product ), // Displayed price
get_woocommerce_currency(), // currency
$search_string
);
$button_html = str_replace($search_string, $replace_string, $button_html);
}
return $button_html;
}
// Below is the jQuery code that will handle the event getting the required product data
// This code needs to be in functions.php
add_action( 'wp_footer', 'added_to_cart_js_event' );
function added_to_cart_js_event(){
?>
<script type="text/javascript">
(function($){
$(document.body).on('added_to_cart', function( event, fragments, cart_hash, button ) {
var product_id = button.data('product_id'), // Get the product id
product_qty = button.data('quantity'), // Get the quantity
product_sku = button.data('product_sku'), // Get the product sku
product_name = button.data('product_name'), // Get the product name
product_price = button.data('product_price'), // Get the product price
currency = button.data('currency'); // Get the currency
// For testing: View all product available data on console log (to be removed)
console.log( button.data() );
//make sure to add webengage SDK in the head section as they suggested in their docs.
//And only then this below script will get triggered.
webengage.track("Added To Cart", {
"Product ID" : product_id,
"Price" : product_price,
"Quantity" : product_qty,
"SKU Code": product_sku,
"Product Name" : product_name,
"Currency" : currency,
});
});
})(jQuery);
</script>
<?php
}
This code will work on shop pages, archive pages, related products and not on single product page. Minor customisation is required for it to run on single product page that you can do it on your own if the above code works on shop page, archive page or related products section. Let me know how this goes.
Jayaram Y comments:
Hi Naveen,
Yes, this is what I need. You are superrrr!!!
Its working now in my archive pages and custom short-codes that i created for home page and blog sliders.
How do I make sure it works on single product page as well?
I see the single product page has button and input hidden values instead of the anchor link that we pass custom data attributes?
Naveen Chand comments:
Hi Jayaram,
Good to know it works.
Does your Single Product Page also works via Ajax? or does it reload the page when add to cart button is clicked? Some themes do not have Ajax for single product pages. Can you share the link of the single product page?
Jayaram Y comments:
Hi Naveen,
So I excluded the given script code from single templates as it was causing issues with single product ajax add to cart as well as in same page related product ajax add to cart.
Its working fine on home, archive and custom shortocode places.
In single product pages, we have variations, and it uses Ajax add to cart only. So whenever user selects the variation, that name, sku, price, and other details need to be passed to webengage now.
Naveen Chand comments:
If you are using Ajax on single product page also, then you can use the same script that I provided earlier. However, you need to make few changes:
1. Wrap the same code I provided in a new function and attach the new function name to wp_footer hook (same like we did earlier but give a different function name).
2. Grab the variables (product_id etc) from the input hidden fields (that you mentioned earlier) using jQuery and put them in place of existing product_id variables [example:
Replace this:
button.data('product_id')
with this
$('input#hiddenFieldID').val(); // make sure you take the correct hiddenFieldID or name as the case may be
I will not be able to provide sample code unless I see the page as I would not know what IDs and names are assigned to the input fields.
Jayaram Y comments:
Hi Naveen,
Here is the product link with variations - https://www.formen.health/product/hair/minoxidil-solution/
In this page, there is a related products custom section that works with your old code.. But as this is a single product page, its getting conflict withe the script given earlier. The top add to cart and related products add to cart need to work on single product templates.
Naveen Chand comments:
The single product template that is used on this page uses some plugins that alter the normal behaviour of default woocommerce setup. Because of this, it is difficult to ascertain which event is triggered on on a single product page on adding item to cart. However, you can add try adding the functions given below to functions.php and try.
add_action('woocommerce_before_add_to_cart_button', 'knc_customfields', 10 );
function knc_customfields {
global $product;
$knc_product_id = $product->get_id();
$knc_product_price = $product->get_price();
$knc_product_sku = $product->get_sku();
$knc_product_name = $product->get_name();
echo '<input type="hidden" name="knc_product_id" id="knc_product_id" value="' .$knc_product_id .'">';
echo '<input type="hidden" name="knc_product_price" id="knc_product_price" value="' .$knc_product_price .'">';
echo '<input type="hidden" name="knc_product_sku" id="knc_product_sku" value="' .$knc_product_sku .'">';
echo '<input type="hidden" name="knc_product_name" id="knc_product_name" value="' .$knc_product_name .'">';
}
add_action( 'wp_footer', 'added_to_cart_js_event_single' );
function added_to_cart_js_event_single(){
?>
<script type="text/javascript">
(function($){
$('.single_add_to_cart_button').click(function() {
var product_id = $('#knc_product_id').val();
var product_qty, product_sku, product_name, product_price, currency;
product_name = $('#knc_product_name').val();
product_qty = $('.single_add_to_cart_button').data('quantity');
if (product_qty == null) {
product_qty = 1;
}
currency = "INR";
if ($('#product-'+product_id).hasClass('product_type_simple')) {
product_price = $('#knc_product_price').val();
product_sku = $('#knc_product_sku').val();
}
if ($('#product-'+product_id).hasClass('product_type_variable')) {
product_price = $('.woovr-variation-active').data('price');
product_sku = $('.woovr-variation-active').data('sku');
}
console.log(product_id+', '+product_price+', '+product_qty+', '+product_sku );
//make sure to add webengage SDK in the head section as they suggested in their docs.
//And only then this below script will get triggered.
webengage.track("Added To Cart", {
"Product ID" : product_id,
"Price" : product_price,
"Quantity" : product_qty,
"SKU Code": product_sku,
"Product Name" : product_name,
"Currency" : currency,
});
});
})(jQuery);
</script>
<?php
}
If you have noticed some of the classes (woovr-variation-active) are added by external plugins.
It is time consuming to test such cases on my own environment where all those plugins and Ajax functionality needs to be added on single product page. So I am giving this code without testing. If you are able to read the code, you may get the right direction to get it working on single product page.