在一阵头痛之后,我设法使它发挥了作用。这是我的代码:
add_action( \'woocommerce_cart_calculate_fees\', \'iom_add_custom_discount\', 10, 1 );
function iom_add_custom_discount( $wc_cart ){
$discount = 0;
$product_ids = array();
$product_ids_disc = array();
$item_prices = array();
$in_cart = false;
foreach ( $wc_cart->get_cart() as $cart_item_key => $cart_item ) {
$cart_product = $cart_item[\'data\'];
// here we check if the products in the cart are in category \'detski-bodita\'.
// since these are variation products, we check if their parents have the category.
// if they do we add them the $in_cart boolean to true.
if ( has_term( \'detski-bodita\', \'product_cat\', $cart_product->get_parent_id() ) ) {
// var_dump(count($in_cart));
$in_cart = true;
$product_ids_disc[] = $cart_product->get_id();
$item_prices[$cart_product->get_id()] = $cart_product->get_price();
} else {
$product_ids[] = $cart_product->get_id();
$item_prices[$cart_product->get_id()] = $cart_product->get_price();
}
}
// here we check if we have products with $in_cart boolean to true
// and if they are in category \'detski-bodita\'
if ( ( $in_cart ) && ( has_term( \'detski-bodita\', \'product_cat\', $cart_product->get_parent_id() ) ) ) {
$count_ids = count($product_ids_disc); // We count the items we have
asort( $item_prices ); // Sort the prices from lowest to highest
$count = 0; // we add another counter for the products that will be discounted.
// here we check if the minimum amount of products is met for the discount.
if( $count_ids >= 3 ) {
foreach( $item_prices as $id => $price ) {
if( $count >= 1 ) {
break;
}
//$product = wc_get_product( $id );
//$price = $product->get_price();
$discount -= ($price * 100) / 100; // this is the discount that we apply - 100%
$count++; // increase the counter in order to stop after the max amount of discounted products
}
}
}
if( $discount != 0 ){
$wc_cart->add_fee( \'Отстъпка\', $discount, true );
# Note: Last argument in add_fee() method is related to applying the tax or not to the discount (true or false)
}
}
我还有一些问题需要解决。仅当购物车中有3件相同类别的商品时,才应使用折扣。例如,类别为t恤和连帽衫。如果我的购物车里有3件t恤,就应该打折。如果我有两件t恤和一件连帽衫,则不应享受折扣。如果我有3件t恤和1件连帽衫,则应享受折扣。但是,我的功能似乎只有在购物车中有来自同一类别的3种不同产品时才起作用。如果我有1件数量为2的t恤和1件数量为1的t恤,那么它不起作用,应该在什么时候应用折扣。此外,如果我在购物车里放了3件t恤和1件连帽衫,然后取下1件t恤,那么在不应该的时候,折扣仍然适用。。任何帮助都将不胜感激。谢谢!:)