简体   繁体   中英

WooCommerce: how to add a number of products to the cart programatically?

I would like to add items in the amount of product chosen by customer every time the add to cart button is clicked,

I tried to modify the number of products using woocommerce_add_to_cart_validation but with variable products it adds the variable product twice to the cart:

function so_validate_add_cart_item( $passed, $product_id, $quantity, $variation_id = '', $variations= '' ) {    
   global $product;
   $product =  new WC_Product($product_id);
   if(!$variation_id) { 

      WC()->cart->add_to_cart( $product_id, ($quantity *3) - $quantity );

    } else { 

      WC()->cart->add_to_cart( $variation_id, ($quantity *3) ); 

    }

    // do your validation, if not met switch $passed to false
    return $passed;

}
add_filter( 'woocommerce_add_to_cart_validation', 'so_validate_add_cart_item', 10, 5 );

Not really an idea what your intention is, but you could use the following hook (not with ajax, check cart after applying)

function my_add_to_cart_quantity( $quantity, $product_id ) {
    $quantity = $quantity * 3;
    return $quantity;
}
add_filter( 'woocommerce_add_to_cart_quantity', 'my_add_to_cart_quantity', 10, 2 );

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