在 Woocommerce 中,我使用此代码在 woocommerce 商店循环中添加数量字段:
/**
* Override loop template and show quantities next to add to cart buttons
*/
add_filter( 'woocommerce_loop_add_to_cart_link', 'quantity_inputs_for_woocommerce_loop_add_to_cart_link', 10, 2 );
function quantity_inputs_for_woocommerce_loop_add_to_cart_link( $html, $product ) {
if ( $product && $product->is_type( 'simple' ) && $product->is_purchasable() && $product->is_in_stock() && ! $product->is_sold_individually() ) {
$html = '<form action="' . esc_url( $product->add_to_cart_url() ) . '" class="cart" method="post" enctype="multipart/form-data">';
$html .= woocommerce_quantity_input( array(), $product, false );
$html .= '<button type="submit" class="button alt">' . esc_html( $product->add_to_cart_text() ) . '</button>';
$html .= '</form>';
}
return $html;
}
此代码工作正常,但它不控制可用的产品数量。
例如,如果产品 A 有 3 件商品,在单个产品页面中我们最多只能添加 3 件商品,但在使用上述代码的商店循环中,我们可以为该产品输入无限数量的商品。
如何解决?