我遵循这条完美运作的线索:
Set discount based on number of orders in WooCommerce。
但在我的情况下,我需要应用折扣不是订单总额,而是运费,我想这样做,只有在一个特定的国家,特别是英国。
例如:
我已经将英国的统一利率设定为6欧元,但我需要了解如何从第二次订单开始,才适用25欧元的附加费。
这是我的代码尝试:
add_filter( 'woocommerce_package_rates', 'free_first_order_shipping', 20, 2 );
function free_first_order_shipping( $rates, $package ) {
if(is_user_logged_in()) {
$user_id = get_current_user_id();
//We want to know how many completed orders customer have or remove status if you dont care.
$args = array(
'customer_id' => 1,
'status' => array('wc-completed'),
);
$orders = wc_get_orders($args);
//If there are no orders returned apply free shipping
if($orders == 0) {
unset( $rates['flat_rate:15'] ); // Shipping 25 euro
}
else{
unset( $rates['betrs_shipping:10-2'] ); // Shipping 6 euro
}
}
return $rates;
}但是,这并不调整成本,而是删除了发货方法。有什么建议吗?
发布于 2022-04-05 09:52:42
关于您的代码尝试/问题的一些注释:
您所指的答案是关于增加(负)费用,country
unset( $rates['flat_rate:15'] )钩子确实比woocommerce_cart_calculate_fees钩子更适合您的问题
$package['destination']['country']来确定
wc_get_customer_order_count()函数H 213f 214所以你得到了:
function filter_woocommerce_package_rates( $rates, $package ) {
// ONLY for specific countries
$specific_countries = array( 'UK', 'BE' );
// Checks if a value (country) exists in an array, if not return
if ( ! in_array( $package['destination']['country'], $specific_countries ) ) return $rates;
// Only for logged in users
if ( is_user_logged_in() ) {
// Get user ID
$user_id = get_current_user_id();
// Get the total orders by a customer.
$count = wc_get_customer_order_count( $user_id );
// Loop through
foreach ( $rates as $rate_key => $rate ) {
// Initialize
$has_taxes = false;
// Targeting "Flat Rate" shipping method
if ( $rate->method_id == 'flat_rate' ) {
// Get the initial cost
$initial_cost = $new_cost = $rates[$rate_key]->cost;
// Based on order count
if ( $count == 0 ) {
// Set the new rate cost
$new_cost = 6;
} else {
// Set the new rate cost
$new_cost = 25;
}
// Set the new cost
$rates[$rate_key]->cost = $new_cost;
// Taxes rate cost (if enabled)
$taxes = [];
// Loop through the shipping taxes array (as they can be many)
foreach ($rates[$rate_key]->taxes as $key => $tax ) {
if ( $rates[$rate_key]->taxes[$key] > 0 ) {
// Get the initial tax cost
$initial_tax_cost = $new_tax_cost = $rates[$rate_key]->taxes[$key];
// Get the tax rate conversion
$tax_rate = $initial_tax_cost / $initial_cost;
// Set the new tax cost
$taxes[$key] = $new_cost * $tax_rate;
// Enabling tax
$has_taxes = true;
}
}
// When true
if ( $has_taxes ) {
$rates[$rate_key]->taxes = $taxes;
}
}
}
}
return $rates;
}
add_filter( 'woocommerce_package_rates','filter_woocommerce_package_rates', 10, 2 );不要忘记清空您的购物车来刷新传送缓存的数据!
https://stackoverflow.com/questions/71743285
复制相似问题