如果客户添加5个产品1附件应该添加,我想根据产品数量强制销售。如果他们添加超过5,添加2个配件。 因此配件应该加上五个的倍数。
答案 0 :(得分:0)
试试这个:
add_action( 'woocommerce_add_to_cart', 'prefix_add_additional_product', 10, 6 );
/**
* Adds additional product to cart based on the quantity of an added product
*/
function prefix_add_additional_product( $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data ) {
// Get the cart
$cart = WC()->cart->get_cart();
// Nothing, if the cart is empty
if ( 0 == count( $cart ) ) {
return;
}
// Enter the free product ID
$additional_product_id = 96;
// Don't add accessory when adding the same accessory
$added_product_id = 0 < $variation_id ? $variation_id : $product_id;
if ( $added_product_id == $additional_product_id ) {
return;
}
// You can add checks for specific product ID or some other requirements here
$additional_product_quantity = (int) ( $quantity / 5 );
WC()->cart->add_to_cart( $additional_product_id, $additional_product_quantity );
}
https://gist.github.com/vanbo/f42cfa8bdf593013f77dda605a9876bb
代码应将$additional_product_id
添加到购物车,其数量与添加的产品与购物车数量之间的数量相差5。
代码被挂钩到add to cart hook。