How to Add Quantity Field On Shop Page for WooCommerce
Today we are going to talk about how to add a quantity field on the shop page for WooCommerce. You have to paste the following function in your active/child theme’s function.php file.
function qaisarsatti_loop_quantity_input() {
global $product;
if ( $product && $product->is_purchasable() && $product->is_type( 'simple' ) && $product->is_in_stock() && ! $product->is_sold_individually() ) {
woocommerce_quantity_input(
array(
'min_value' => 1,
'max_value' => $product->backorders_allowed() ? '' : $product->get_stock_quantity(),
)
);
}
}
add_action( 'woocommerce_after_shop_loop_item', 'qaisarsatti_loop_quantity_input', 9 );
global $product;
if ( $product && $product->is_purchasable() && $product->is_type( 'simple' ) && $product->is_in_stock() && ! $product->is_sold_individually() ) {
woocommerce_quantity_input(
array(
'min_value' => 1,
'max_value' => $product->backorders_allowed() ? '' : $product->get_stock_quantity(),
)
);
}
}
add_action( 'woocommerce_after_shop_loop_item', 'qaisarsatti_loop_quantity_input', 9 );
Add js to add quantity
function qaisarsatti_add_qty_change_script() {
?>
<script>
(function ($) {
$(document).on("change", "li.product .quantity input.qty", function (e) {
e.preventDefault();
var add_to_cart_button = $(this).closest("li.product").find("a.add_to_cart_button");
// For AJAX add-to-cart actions.
add_to_cart_button.attr("data-quantity", $(this).val());
// For non-AJAX add-to-cart actions.
add_to_cart_button.attr("href", "?add-to-cart=" + add_to_cart_button.attr("data-product_id") + "&quantity=" + $(this).val());
});
})(jQuery);
</script>
<?php
}
add_action( 'wp_head', 'qaisarsatti_add_qty_change_script', 20 );
?>
<script>
(function ($) {
$(document).on("change", "li.product .quantity input.qty", function (e) {
e.preventDefault();
var add_to_cart_button = $(this).closest("li.product").find("a.add_to_cart_button");
// For AJAX add-to-cart actions.
add_to_cart_button.attr("data-quantity", $(this).val());
// For non-AJAX add-to-cart actions.
add_to_cart_button.attr("href", "?add-to-cart=" + add_to_cart_button.attr("data-product_id") + "&quantity=" + $(this).val());
});
})(jQuery);
</script>
<?php
}
add_action( 'wp_head', 'qaisarsatti_add_qty_change_script', 20 );