У меня возникли проблемы с управлением современными купонами и специальными дополнительными полями на странице корзины и выписки.Управление условными купонами и дополнительными комиссиями в корзине/оформлении заказа Woocommerce
Я создал функцию, которая добавляет скидку только в том случае, если продукт присутствует в корзине с более чем вариацией, а скидка применяется только на втором (или третьем) варианте, а не на первом. Вы можете найти мой последний код здесь Woocommerce conditional part cart discount on the same product present with > 1 variation
Однако мне пришлось идти дальше, так как у меня особенно сложная ситуация. Обычно условие, описанное выше, не может применяться, когда в корзине действуют другие скидки (например, стандартные купоны на скидку). Поэтому я добавил эти две строки сразу после получения тележки
$has_coupons = count(WC()->cart->applied_coupons)>0?true:false;
if(!$has_coupons) {
//here goes the function that I did
} else return;
Все в порядке, и это работает. Однако есть особая ситуация, в которой я должен применить купон к телеге (а не%), что умаляет всю корзину определенной суммы. Этот конкретный купон может идти со скидкой, созданной в функции, которую я написал!
/* get coupon code*/
function get_coupon_code() {
global $woocommerce;
if (!empty($woocommerce->cart->applied_coupons)) {
$my_coupon_code = $woocommerce->cart->get_coupons() ;
foreach($my_coupon_code as $coupon){
if ($post = get_post($coupon->id)) {
$coupon_code= $coupon->code;
}
}
}
return $coupon_code;
}
/* get coupon amount*/
function get_coupon_amount() {
global $woocommerce;
if (! empty($woocommerce->cart->applied_coupons)) {
$my_coupon_amount = $woocommerce->cart->get_coupons() ;
foreach($my_coupon_amount as $coupon){
$coupon_amount =$coupon->coupon_amount;
}
}
return $coupon_amount;
}
function cart_discount() {
if (is_admin() && ! defined('DOING_AJAX'))
return;
global $woocommerce;
//get the code and amount of the coupon applied
$coupon_code = get_coupon_code();
$coupon_amount = get_coupon_amount();
//check if the code corresponds to the coupon exception I want to accept
if ($coupon_code == 'wa-1'){
//if it is the code I need to apply, then I remove it from the cart
WC()->cart->remove_coupon($coupon_code);
//I use the amount to add it as additional fee at negative
$coupon_discount = -($coupon_amount);
//I add the ex-coupon amount to an additional field
$discount_agency_text = __('Detracted agency fee', 'woocommerce');
WC()->cart->add_fee($discount_agency_text, $coupon_discount, false);
}
//and following the function previously mentioned
$cart = WC()->cart->get_cart();
$has_coupons = count(WC()->cart->applied_coupons)>0?true:false;
//check if there are other coupons or if the coupon applied are the case I want to pass through my function
if(!$has_coupons || $coupon == 'wa-1') {
//here follows the strings to apply a 10% discount on the second (third) variation of the product and not on the first one
foreach($cart as $cart_item_key => $values) {
$product_id = $values['product_id']; // product ID
$variation_id = $values['variation_id']; // product quantity
$cart_lines_total = $values["line_total"];
$cart_lines_quantity = $values["quantity"];
//product id to be considered for this discount
//$product = 1394 = Spedizioni CSR eng
//$product = 1389 = Spedizioni IDP eng
//$product = 13888 = Spedizioni CSR ita
//$product = 13910 = Spedizioni IDP ita
if($product_id == '1394' || $product_id == '1389' || $product_id == '13888' || $product_id == '13910')
{
$cart_array []= array($product_id , $variation_id, $cart_lines_quantity, $cart_lines_total);
}
}
$conteggio = count($cart_array); //counts the number of items in teh cart
// percent is 5%
$percent = -0.10;
if ($conteggio < 3 && $cart_array[0][0] == $cart_array[1][0])
{
$discount = $percent * $cart_array[1][3];
$discount_text = __('10% discount on subsequent week(s)', 'woocommerce');
WC()->cart->add_fee($discount_text, $discount, false);
}
if ($conteggio < 4 && $cart_array[0][0] == $cart_array[1][0] && $cart_array[0][0] == $cart_array[2][0])
{
$discount = ($percent * $cart_array[1][3]) + ($percent * $cart_array[2][3]);
$discount_text = __('10% discount on subsequent week(s)', 'woocommerce');
WC()->cart->add_fee($discount_text, $discount, false);
}
if ($conteggio < 5 && $cart_array[0][0] == $cart_array[1][0] && $cart_array[0][0] == $cart_array[2][0] && $cart_array[0][0] == $cart_array[3][0])
{
$discount = ($percent * $cart_array[1][3]) + ($percent * $cart_array[2][3]) + ($percent * $cart_array[3][3]);
$discount_text = __('10% discount on subsequent week(s)', 'woocommerce');
WC()->cart->add_fee($discount_text, $discount, false);
}
} else return;
}
add_action('woocommerce_cart_calculate_fees','cart_discount');
Проблема у меня есть то, что часть касается управления купоном на скидку не работает. Он получает $ coupon_code и $ coupon_amount, но не добавляет его в раздел дополнительных полей.
Кто-нибудь может мне помочь?
ссылки очень приветствуются в ответах, но ответы всегда должны представить необходимую информацию по ссылке, поскольку ссылки могут измениться. Спасибо! – Alex