简体   繁体   中英

Woocommerce multiply the quantity of a specific product in cart

Is there any way to multiply the quantity of specific product in cart?

Lets say I have multiple products in the cart and one of the products has quantity "3", I want to multiply the quantity with "5" so [3*5] and update the quantity field to "15".

I want to do it for only one specific product in cart and not for all.

It depends where and when you want to change it.

I can think of two different approaches:

PHP:

$woocommerce->cart->set_quantity( product_id , product_quantity );

JS + AJAX:

You can find a working solution here, just try to adapt it to your needs:

WooCommerce - change QTY triggers AJAX call in cart

EDIT:

I've coded a simple jQuery example. You can do this on real time while user inputs the quantity in the cart amount input. The user inputs any quantity and when he/she clicks outside or leaves the input focus the amount is automatically changed (x5).

In order to use this you have to edit the cart template in Wordpress. I would strongly recommend using a child theme and following the Woocommerce template best practices .

 $("#input-value").focusout(function() { var value = parseFloat($(this).val()); $(this).val(value*5); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> Quantity: <input type="text" id="input-value" /> 

In order to aim for only a specific product you an use some PHP in your cart template to add a 'multiply' class to the quantity container:

<?php if($_product->id == your_id) {
?>
    <td class="product-quantity multiply" data-title="<?php _e( 'Quantity', 'woocommerce' ); ?>">
<?php
}else{
?>
    <td class="product-quantity" data-title="<?php _e( 'Quantity', 'woocommerce' ); ?>">
<?php
}
?>

    <?php
        if ( $_product->is_sold_individually() ) {
            $product_quantity = sprintf( '1 <input type="hidden" name="cart[%s][qty]" value="1" />', $cart_item_key );
        } else {
            $product_quantity = woocommerce_quantity_input( array(
                'input_name'  => "cart[{$cart_item_key}][qty]",
                'input_value' => $cart_item['quantity'],
                'max_value'   => $_product->backorders_allowed() ? '' : $_product->get_stock_quantity(),
                'min_value'   => '0'
            ), $_product, false );
        }

        echo apply_filters( 'woocommerce_cart_item_quantity', $product_quantity, $cart_item_key, $cart_item );
    ?>
</td>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM