Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
程式化 WooCommerce 運費折扣
<?php
function mxp_shipping_fee_discount() {
$fee = 0; // 新增運費底價
if (is_admin() && !defined('DOING_AJAX')) {
// 避免在管理介面下被觸發
return;
}
$total_pirce = 0;
foreach (WC()->cart->get_cart() as $item => $values) {
// 撈取購物車中的每一個商品
$_product = wc_get_product($values['data']->get_id());
// 商品名稱
$product_name = $_product->get_title();
// 商品數量
$qty = $values['quantity'];
// 商品價格
$total_price += $_product->get_price();
// 商品設定的運送類別
$shipping_class = $_product->get_shipping_class();
}
foreach (WC()->session->get('shipping_for_package_0')['rates'] as $method_id => $rate) {
// 判斷當前選擇的運送方法與目前購物車總金額是否大於 699
if (WC()->session->get('chosen_shipping_methods')[0] == $method_id && $total_price >= 699) {
$rate_label = $rate->label; // 當前運費標籤名稱
$rate_cost_excl_tax = floatval($rate->cost); // 不含稅率的運費
// 紀錄稅率費用
$rate_taxes = 0;
foreach ($rate->taxes as $rate_tax) {
$rate_taxes += floatval($rate_tax);
}
// 包含稅率費用的總運費
$rate_cost_incl_tax = $rate_cost_excl_tax + $rate_taxes;
if ($rate_cost_incl_tax != 0) {
WC()->cart->add_fee('滿699免運費', -$rate_cost_incl_tax, false);
}
break;
}
}
}
add_action('woocommerce_cart_calculate_fees', 'mxp_shipping_fee_discount');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.