Auto trigger Update on quantity change in WooCommerce cart page
To make it work, you need to delegate the "change" event to the document body, this way:
add_action( 'wp_footer', 'auto_update_cart_on_qty_change' );
function auto_update_cart_on_qty_change() {
if ( is_cart() ) :
?>
<script type="text/javascript">
(function($){
$( document.body ).on( 'change input', 'input.qty', function() {
$('[name=update_cart]').trigger('click');
});
})(jQuery);
</script>
<?php
endif;
}
Code goes in functions.php file of the active child theme (or active theme). Tested and works.
Added also "input" event when customer input a value in the quantity field.
Auto update cart on quantity change in Woocommerce cart page
Just to make this question somewhat useful for anyone who reads here in the future.. here is the script that ended up working for me. I found the answer here from this helpful guide.
jQuery('div.woocommerce').on('click', 'input.qty', function(){
jQuery("[name='update_cart']").trigger("click");
});
Auto update cart totals on cart item quantity change in Woocommerce
You need to use it as a document.body delegated event (on change
and input
events) as follow:
add_action( 'wp_footer', 'update_cart_on_item_qty_change');
function update_cart_on_item_qty_change() {
if (is_cart()) :
?>
<script type="text/javascript">
jQuery( function($){
$(document.body).on('change input', '.qty', function(){
$('button[name="update_cart"]').trigger('click');
// console.log('Cart quantity changed…');
});
});
</script>
<?php
endif;
}
Code goes in functions.php file of your active child theme (or active theme). Tested and work.
Similar: Avoid a function to only runs once on button click in WooCommerce cart
Update cart with WooCommerce ajax
You have forget this essential process:
add_action('wp_enqueue_scripts', 'add_my_ajax_scripts');
function add_my_ajax_scripts() {
// Here you register your script located in a subfolder `js` of your active theme
wp_enqueue_script( 'ajax-script', get_template_directory_uri().'/js/script.js', array('jquery'), '1.0', true );
// Here you are going to make the bridge between php and js
wp_localize_script( 'ajax-script', 'cart_ajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
Then you will retrieve "ajaxurl
" and "cart_ajax
" in your javascript file in "url:
":
$.ajax({
url: cart_ajax.ajaxurl,
...
})
Your javascript function will not work. Here are some functional examples of what you need to do:
WooCommerce - auto update total price when quantity changed?
Wordpress passing ajax value to a specific page using Wordpress
Using AJAX With PHP on Your WordPress Site Without a Plugin
How to use Ajax with your WordPress Plugin or Theme?
Automatically recalculate quantity when clicking on update cart in Woocommerce
Preliminary remarks:
Your code doesn't work when cart is empty as
$bonus
variable is not defined and you get an error…Also as you are setting a variable float number for quantity: So if the quantity is not an integer, customer can't change and update the cart items quantities.
This is kind of complex, your bonus quantity need to be updated in another hooked function when:
- A product is added to cart
- Customer update quantities in cart page
- Customer remove items from cart
Also, there is small errors like $_product->id
that should instead $_product->get_id()
in WC 3+
So your revisited code with additional hooked functions will be:
add_action( 'template_redirect', 'auto_add_product_to_cart', 50 );
function auto_add_product_to_cart() {
if ( ! is_admin() ) {
$cart = WC()->cart; // <== Cart object
$product_id = 37; // <== Specific product to be auto added
$bonus_rate = .25; // <== Bonus rate
$found = false;
// Check if product already in cart
if ( ! $cart->is_empty() ) {
$contents_count = $cart->get_cart_contents_count(); // The cart items count
$bonus_qty = $contents_count * $bonus_rate; // Bonus quantity calculation
// Loop through cart items
foreach ( $cart->get_cart() as $cart_item ) {
if ( $cart_item['data']->get_id() == $product_id ){
$found = true;
break; // Stop the loop
}
}
// Product is not found in the loop, we add it
if( ! $found )
$cart->add_to_cart( $product_id, $bonus_qty );
} else {
// There is no items in cart, we add it
$cart->add_to_cart( $product_id, $bonus_rate );
}
}
}
// Calculate, set and update bonus quantity
add_action( 'woocommerce_before_calculate_totals', 'conditional_bonus_quantity_calculation', 20, 1 );
function conditional_bonus_quantity_calculation( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
$bonus_rate = .25; // <== Bonus rate
$product_id = 37; // <== Specific product to be auto added
$contents_count = $cart->get_cart_contents_count(); // Total cart items count
// Loop through cart items to check our specific product
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
// If specific product is in cart
if ( $cart_item['data']->get_id() == $product_id ){
$calc_qty = $cart_item['quantity'] < 1 ? 1 : $cart_item['quantity'];
// Bonus quantity calculation
if( $contents_count > 1 )
$bonus_qty = round( $contents_count - $calc_qty ) * $bonus_rate;
else
$bonus_qty = $bonus_rate;
// Update item quantity
$cart->set_quantity( $cart_item_key, $bonus_qty, false );
}
}
}
// Allowing float numbers quantity (step by .25) for a specific product
add_filter( 'woocommerce_quantity_input_args', 'custom_quantity_input_args', 20, 2 );
function custom_quantity_input_args( $args, $product ) {
// Only for your specific product ID on cart page
if( $product->get_id() != 37 && is_cart() ) return $args;
//$args['input_value'] = 0.25; // Default starting value (Optional)
$args['min_value'] = 0.25;
$args['step'] = 0.25;
$args['pattern'] = '[0-9.]*';
$args['inputmode'] = 'numeric';
return $args;
}
// Allowing float numbers in Stock management
remove_filter('woocommerce_stock_amount', 'intval');
add_filter('woocommerce_stock_amount', 'floatval');
Code goes in function.php file of the active child theme (or active theme).
Tested and works.
Related Topics
How to Parse a Json File With PHP
How to Bind an Array to an In() Condition in a Pdo Query
MySQLi or Die, Does It Have to Die
How to Implement Basic "Long Polling"
Send Email Using the Gmail Smtp Server from a PHP Page
Turning Query Errors to Exceptions in MySQLi
MySQLi or Pdo - What Are the Pros and Cons
How to Check If a String Contains a Specific Word
How to Apply Bindvalue Method in Limit Clause
Should We Ever Check For MySQLi_Connect() Errors Manually
How to Configure Xampp to Send Mail from Localhost
How to Convert Ereg Expressions to Preg in PHP
PHP - Failed to Open Stream: No Such File or Directory
Calculate Size in Bytes of Json Payload Including It in the Json Payload in PHP