반응형
Woocommerce 3.2+의 주문에 프로그래밍 방식으로 할인 추가
woocommerce에서는 쿠폰 기능(고정금액, 백분율...)을 사용하여 모든 주문에 할인을 추가할 수 있습니다.
할인금액이 얼마든지 될 수 있는 주문에 할인금액을 추가할 수 있습니까?
어떤 도움이라도 주시면 감사하겠습니다.
주문에 대해 프로그래밍 방식으로 할인을 할 수 있는 유일한 기능은 수수료 API를 속이는 것입니다.참고로 이 트릭은 쿠폰 외 Woocommerce에는 할인 기능이 없기 때문에 woocommerce에서는 권장하지 않지만 많은 사람들이 사용하고 있습니다.
다음 기능을 통해 금액 또는 백분율을 고정 할인할 수 있습니다.순서가 존재해야 합니다(이전에 저장해야 합니다).
함수 코드(Woocommerce 버전 3.2+의 경우):
/**
* Add a discount to an Orders programmatically
* (Using the FEE API - A negative fee)
*
* @since 3.2.0
* @param int $order_id The order ID. Required.
* @param string $title The label name for the discount. Required.
* @param mixed $amount Fixed amount (float) or percentage based on the subtotal. Required.
* @param string $tax_class The tax Class. '' by default. Optional.
*/
function wc_order_add_discount( $order_id, $title, $amount, $tax_class = '' ) {
$order = wc_get_order($order_id);
$subtotal = $order->get_subtotal();
$item = new WC_Order_Item_Fee();
if ( strpos($amount, '%') !== false ) {
$percentage = (float) str_replace( array('%', ' '), array('', ''), $amount );
$percentage = $percentage > 100 ? -100 : -$percentage;
$discount = $percentage * $subtotal / 100;
} else {
$discount = (float) str_replace( ' ', '', $amount );
$discount = $discount > $subtotal ? -$subtotal : -$discount;
}
$item->set_tax_class( $tax_class );
$item->set_name( $title );
$item->set_amount( $discount );
$item->set_total( $discount );
if ( '0' !== $item->get_tax_class() && 'taxable' === $item->get_tax_status() && wc_tax_enabled() ) {
$tax_for = array(
'country' => $order->get_shipping_country(),
'state' => $order->get_shipping_state(),
'postcode' => $order->get_shipping_postcode(),
'city' => $order->get_shipping_city(),
'tax_class' => $item->get_tax_class(),
);
$tax_rates = WC_Tax::find_rates( $tax_for );
$taxes = WC_Tax::calc_tax( $item->get_total(), $tax_rates, false );
print_pr($taxes);
if ( method_exists( $item, 'get_subtotal' ) ) {
$subtotal_taxes = WC_Tax::calc_tax( $item->get_subtotal(), $tax_rates, false );
$item->set_taxes( array( 'total' => $taxes, 'subtotal' => $subtotal_taxes ) );
$item->set_total_tax( array_sum($taxes) );
} else {
$item->set_taxes( array( 'total' => $taxes ) );
$item->set_total_tax( array_sum($taxes) );
}
$has_taxes = true;
} else {
$item->set_taxes( false );
$has_taxes = false;
}
$item->save();
$order->add_item( $item );
$order->calculate_totals( $has_taxes );
$order->save();
}
코드가 기능합니다.php 파일(액티브 테마)입니다(액티브 테마).테스트 및 동작.
사용 예:
1) 고정할인(다이나믹 포함)$order_id
):
wc_order_add_discount( $order_id, __("Fixed discount"), 12 );
2) (다이나믹 포함)의 %할인$order_id
):
wc_order_add_discount( $order_id, __("Discount (5%)"), '5%' );
양(또는 비율)도 동적 변수가 될 수 있습니다.
실제로 세금 등의 계산 전에 훅을 만들고, 소계를 내고, 할인을 적용하고, 완료하면 됩니다.주문 메시지 등에 자동으로 적용되며, 백엔드에도 올바르게 표시됩니다.훅을 제거한 후에도 할인 정보는 그대로 유지됩니다.
// Hook before calculate fees
add_action('woocommerce_cart_calculate_fees' , 'add_user_discounts');
/**
* Add custom fee if more than three article
* @param WC_Cart $cart
*/
function add_user_discounts( WC_Cart $cart ){
//any of your rules
// Calculate the amount to reduce
$discount = $cart->get_subtotal() * 0.5;
$cart->add_fee( 'Test discount 50%', -$discount);
}
언급URL : https://stackoverflow.com/questions/52646869/add-a-discount-programmatically-to-an-order-in-woocommerce-3-2
반응형
'sourcecode' 카테고리의 다른 글
Redx를 사용한 리액트 라우터 변경에 대응하여 새 데이터를 가져오는 방법 (0) | 2023.03.29 |
---|---|
화면에 [Object Object]가 아닌 JSON 표현을 표시하는 방법 (0) | 2023.03.29 |
ORA-00972 식별자가 너무 깁니다. 별칭 열 이름입니다. (0) | 2023.03.29 |
React 구성 요소에서 사용자 지정 함수 생성 (0) | 2023.03.29 |
C#을 사용하여 서버에 JSON을 게시하려면 어떻게 해야 합니까? (0) | 2023.03.29 |