To automatically update the cart in WooCommerce when the quantity of a product is changed, you can use JavaScript/jQuery to handle the quantity change event and make an AJAX request to update the cart contents.
Solutions:
Open the functions.php file using a text editor and add the following code:
/**
* Snippet Name: To Create custom WooCommerce order status.
* Snippet Author: https://wpproblog.com
*/
add_action( 'wp_footer', 'wpproblog_update_cart_on_quantity_change');
function wpproblog_update_cart_on_quantity_change() { ?>
<script>
jQuery( function( $ ) {
let timeout;
$('.woocommerce').on('change', 'input.qty', function(){
if ( timeout !== undefined ) {
clearTimeout( timeout );
}
timeout = setTimeout(function() {
$("[name='update_cart']").trigger("click");
}, 1000 );
});
} );
</script>
<?php }
//Now, hide the Update Cart button
add_action( 'wp_head', 'ecommercehints_hide_update_cart_button' );
function ecommercehints_hide_update_cart_button() { ?>
<style>
button[name="update_cart"], input[name="update_cart"] {
display: none;
}
</style>
<?php }
Save the changes to the functions.php file or your custom plugin file.
Output:
This code adds a JavaScript event listener to the .quantity input elements within the cart form. Whenever the quantity value is changed, it makes an AJAX request to the update_cart action, passing the cart item key and the new quantity value. The server-side code handles the update and returns the updated cart contents. The success callback function replaces the cart form contents with the updated HTML.
Leave a Review