这是一个快速片段,您可以简单地复制/粘贴以在 WooCommerce 单一产品页面上输入的数量编号的每一侧显示“+”和“-”。
该片段还附带一个 jQuery 脚本,因为我们需要检测是否单击了加号或减号并因此更新数量输入。jQuery 对很多人来说可能看起来很难,但它的美妙之处在于您不需要拥有 jQuery 学位——只需复制/粘贴,然后看看奇迹发生。
PHP 代码段:显示加号和减号数量按钮 @ WooCommerce 单个产品页面和购物车页面
注意:您可能还需要一些自定义 CSS,因为您的主题可能会为数量按钮提供“浮动”显示(默认情况下 HTML 按钮采用内联块)。
/**
* @snippet Plus Minus Quantity Buttons @ WooCommerce Product Page & Cart
* @how-to Get CustomizeWoo.com FREE
* @author Rodolfo Melogli
* @compatible WooCommerce 5
* @donate $9 https://businessbloomer.com/bloomer-armada/
*/
// ————-
// 1. Show plus minus buttons
add_action( ‘woocommerce_after_quantity_input_field’, ‘bbloomer_display_quantity_plus’ );
function bbloomer_display_quantity_plus() {
echo ‘<button type=”button” class=”plus”>+</button>’;
}
add_action( ‘woocommerce_before_quantity_input_field’, ‘bbloomer_display_quantity_minus’ );
function bbloomer_display_quantity_minus() {
echo ‘<button type=”button” class=”minus”>-</button>’;
}
// ————-
// 2. Trigger update quantity script
add_action( ‘wp_footer’, ‘bbloomer_add_cart_quantity_plus_minus’ );
function bbloomer_add_cart_quantity_plus_minus() {
if ( ! is_product() && ! is_cart() ) return;
wc_enqueue_js( “
$(document).on( ‘click’, ‘button.plus, button.minus’, function() {
var qty = $( this ).parent( ‘.quantity’ ).find( ‘.qty’ );
var val = parseFloat(qty.val());
var max = parseFloat(qty.attr( ‘max’ ));
var min = parseFloat(qty.attr( ‘min’ ));
var step = parseFloat(qty.attr( ‘step’ ));
if ( $( this ).is( ‘.plus’ ) ) {
if ( max && ( max <= val ) ) {
qty.val( max ).change();
} else {
qty.val( val + step ).change();
}
} else {
if ( min && ( min >= val ) ) {
qty.val( min ).change();
} else if ( val > 1 ) {
qty.val( val – step ).change();
}
}
});
” );
}
评论0