Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cuocsongso/4298ae926240e84bca2a698421015b24 to your computer and use it in GitHub Desktop.
Save cuocsongso/4298ae926240e84bca2a698421015b24 to your computer and use it in GitHub Desktop.
[Besa Theme] - How To Add A Quantity Field To Shop Pages In WooCommerce
/* [Besa Theme] - How To Add A Quantity Field To Shop Pages In WooCommerce */
function thembay_shop_page_add_quantity_field() {
/** @var WC_Product $product */
$product = wc_get_product( get_the_ID() );
if ( ! $product->is_sold_individually() && 'variable' != $product->get_type() && $product->is_purchasable() && $product->is_in_stock() ) {
woocommerce_quantity_input( array( 'min_value' => 1, 'max_value' => $product->backorders_allowed() ? '' : $product->get_stock_quantity() ) );
}
}
add_action( 'woocommerce_after_shop_loop_item', 'thembay_shop_page_add_quantity_field', 1 );
/**
* Add required JavaScript.
*/
function thembay_shop_page_quantity_add_to_cart_handler() {
wc_enqueue_js( '
$(".woocommerce .products").on("click", ".quantity input", function() {
return false;
});
$(".woocommerce .products").on("change input", ".quantity .qty", function() {
var add_to_cart_button = $(this).parents( ".product" ).find(".add_to_cart_button");
add_to_cart_button.attr("data-quantity", $(this).val())
});
// Trigger on Enter press
$(".woocommerce .products").on("keypress", ".quantity .qty", function(e) {
if ((e.which||e.keyCode) === 13) {
$( this ).parents(".product").find(".add_to_cart_button").trigger("click");
}
});
' );
}
add_action( 'init', 'thembay_shop_page_quantity_add_to_cart_handler' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment