so i have woocommerce based shop, and im selling for example CAKE if customer adds 4 cakes, i want 1 box to be added in the cart automatically, if customer adds more than 4 cakes i want to add another box (different product id), and so on. here is my code which im doing it:
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 ) {
$category = 'test';
// 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 = 2832;
$additional_product_idd = 2831;
$additional_product_iddd = 2833;
// 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;
}
if( has_term( $category, $product_id ) ){
$cart_id = WC()->cart->generate_cart_id( $additional_product_id );
$prod_in_cart = WC()->cart->find_product_in_cart( $cart_id );
}
// You can add checks for specific product ID or some other requirements here
if( $additional_product_quantity = (int) ( $quantity < 4 )){
if( ! $quantity < 4) {
WC()->cart->add_to_cart( $additional_product_id, $additional_product_quantity ); }
}
elseif( $additional_product_quantity = (int) ( $quantity > 4 )){
WC()->cart->add_to_cart( $additional_product_idd, $additional_product_quantity );
}
}
code is working normally, but problem is that, when i add more than 5 cakes in the cart it still adds box which should be added only if im buying less than 4 cakes, what am i doing wrong here?
Aucun commentaire:
Enregistrer un commentaire