2017-12-13 32 views
2

사용자가 처음으로 주문하는 경우 세금이 계산되기 전에 장바구니 부분합에 할인을 적용해야합니다. 그러나 세금은 WooCommerce에서 항목 당 계산되어 나중에 부분 합계에 추가됩니다. 그래서 WooCommerce가 세금을 계산하기 전에 카트의 항목에 할인을 적용해야합니다. 이 방법은 세금이 원래 가격보다 할인 된 가격에 근거합니다. 여기 WooCommerce에서 세금 제외 카트 내용 합계에 대한 할인 적용

내가 무엇을 가지고 :

function first_order_add_five_percent_discount($cart_object) { 

    if (is_user_logged_in()) { 
     //current user id 
     $currentUser_id = get_current_user_id(); 
     //amount of orders by current user 
     $orderAmount = wc_get_customer_order_count($currentUser_id); 

     //if user has 0 orders... 
     if ($orderAmount == 0) { 
      //for each item in cart 
      foreach ($cart_object->get_cart() as $item_values) { 

       //$item_id = $item_values['data']->id; // Product ID 
       $item_qty = $item_values['quantity']; // Item quantity 
       $original_price = $item_values['data']->price; // Product original price 
       echo $original_price . "<br>"; 
       $totalPrice = $original_price * $item_qty; 
       $discountedPrice = $totalPrice * .05; 
       $newPrice = $original_price - $discountedPrice; 
       echo $totalPrice . "<br>"; 
       echo $discountedPrice . "<br>"; 
       echo $newPrice . "<br>"; 
       $item_values['data']->set_price($newPrice); 

      } 

     } else { 
      //do nothing 
     } 
    } 
} 

add_action('woocommerce_before_calculate_totals', 'first_order_add_five_percent_discount'); 

이 내가 필요로하는 바로 번호를 메아리,하지만 지금은 장바구니에 그 가격을 적용해야합니다. 지금 카트의 가격은 변하지 않습니다.

이 함수의 계산에서 카트에 새로운 가격을 적용하려면 어떻게해야합니까?

답변

2

훨씬 더 간단한 방법이 있는데, 음수 요금을 사용하는 것입니다. 이므로 할인입니다. 어떤 플러그인 파일도

add_action('woocommerce_cart_calculate_fees','new_customers_discount', 10, 1); 
function new_customers_discount($wc_cart) { 
    if (is_admin() && ! defined('DOING_AJAX')) return; // We exit 

    // Only for logged in users 
    if (! is_user_logged_in()) return; // We exit 

    // Only for new customers without orders 
    if (wc_get_customer_order_count(get_current_user_id()) != 0) return; // We exit 

    // discount percentage 
    $percent = 5; 

    // Calculation 
    $discount = $wc_cart->cart_contents_total * $percent/100; 

    // Add the fee (TAX third argument is disabled: false) 
    $wc_cart->add_fee(__('Discount', 'woocommerce')." ($percent%)", -$discount, false); 
} 

코드 활성 자식 테마 (또는 테마)의 function.php 파일에 간다 나 : 그것은 WC_Cart 당신이 세금을 해제 할 수 있습니다 방법 add_fee()를 사용합니다.

테스트 및 작동 중. 당신은 같은 것을 얻을 것이다 :

enter image description here

당신이 할인 카트 내용 전체 제외에 하녀입니다 볼 수 있듯이. 세금

+1

늦게 응답 해 주셔서 죄송합니다. 다른 이상한 세금 관련 문제를 해결하기 위해 노력하고있었습니다. 하지만 네, 맞습니다! 할인 적용 후 세금이 계산됩니다. 완벽한 감사합니다. –