| 1 |
<?php namespace TierPricingTable\Addons\ProductCatalogLoop; |
| 2 |
|
| 3 |
use TierPricingTable\TierPricingTablePlugin; |
| 4 |
|
| 5 |
class QuantityFieldHandler { |
| 6 |
|
| 7 |
public function __construct() { |
| 8 |
add_action( 'woocommerce_after_shop_loop_item', array( $this, 'renderQuantityField' ), 9 ); |
| 9 |
add_action( 'wp_enqueue_scripts', array( $this, 'enqueueQuantityHandlerScript' ) ); |
| 10 |
} |
| 11 |
|
| 12 |
public function renderQuantityField() { |
| 13 |
$product = wc_get_product( get_the_ID() ); |
| 14 |
|
| 15 |
if ( $product && ( TierPricingTablePlugin::isSimpleProductSupported( $product ) ) && ! $product->is_sold_individually() && $product->is_purchasable() && $product->is_in_stock() ) { |
| 16 |
woocommerce_quantity_input( array( |
| 17 |
'min_value' => 1, |
| 18 |
'max_value' => $product->backorders_allowed() ? '' : $product->get_stock_quantity(), |
| 19 |
) ); |
| 20 |
} |
| 21 |
} |
| 22 |
|
| 23 |
public function enqueueQuantityHandlerScript() { |
| 24 |
|
| 25 |
$handle = 'tpt-catalog-quantity-input-handler'; |
| 26 |
|
| 27 |
wp_register_script( $handle, '', array( 'jquery' ), TierPricingTablePlugin::VERSION, true ); |
| 28 |
|
| 29 |
wp_enqueue_script( $handle ); |
| 30 |
|
| 31 |
$inlineJs = ' |
| 32 |
jQuery(".type-product").on("click", ".quantity input", function() { |
| 33 |
return false; |
| 34 |
}); |
| 35 |
|
| 36 |
jQuery(".type-product").on("change input", ".quantity .qty", function() { |
| 37 |
var add_to_cart_button = jQuery(this).closest(".product").find(".add_to_cart_button"); |
| 38 |
|
| 39 |
// For AJAX add-to-cart actions |
| 40 |
add_to_cart_button.attr("data-quantity", jQuery(this).val()); |
| 41 |
|
| 42 |
// For non-AJAX add-to-cart actions |
| 43 |
add_to_cart_button.attr("href", "?add-to-cart=" + add_to_cart_button.attr("data-product_id") + "&quantity=" + jQuery(this).val()); |
| 44 |
}); |
| 45 |
|
| 46 |
// Trigger on Enter press |
| 47 |
jQuery(".woocommerce .products").on("keypress", ".quantity .qty", function(e) { |
| 48 |
if ((e.which || e.keyCode) === 13) { |
| 49 |
jQuery(this).parents(".product").find(".add_to_cart_button").trigger("click"); |
| 50 |
} |
| 51 |
}); |
| 52 |
'; |
| 53 |
|
| 54 |
wp_add_inline_script( $handle, $inlineJs ); |
| 55 |
} |
| 56 |
} |
| 57 |
|