我有一个使用WooCommerce插件的WordPress网站。如果他们选择当地皮卡作为运输方式,我想为买家提供5%的购物总额减免。
我已经尝试过 - 5 * [数量]它似乎没有用。
我也试过-0.95 * [费用]但没有运气
我正在使用WooCommerce 3并通过在活动主题的function.php中编写一个函数来实现上述结果。
function prefix_add_discount_line( $cart ) {
$chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
$chosen_shipping_no_ajax = $chosen_methods[0];
if ( 0 === strpos( $chosen_shipping_no_ajax, 'local_pickup' ) ) {
$discount = $cart->subtotal * 0.05;
$cart->add_fee( __( 'Collection discount applied', 'yourtext-domain' ) , -$discount );
}
}
add_action( 'woocommerce_cart_calculate_fees', 'prefix_add_discount_line');
费用API的问题在于它总是使用税收来收取负费用(折扣)并且不关心现有的优惠券折扣。
下面的代码将设置定义的折扣百分比在运输方式“本地提货”本身。
您需要使用简单的初始成本而不是公式设置参考运费。它可以是例如10
,并将被代码折扣取代。
您可能必须在“运输选项”选项卡下的常规运输设置中“启用调试模式”,以禁用临时运输缓存。
代码(您将在其中设置折扣百分比):
add_filter('woocommerce_package_rates', 'local_pickup_percentage_discount', 12, 2);
function local_pickup_percentage_discount( $rates, $package ){
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return $rates;
// HERE define the discount percentage
$percentage = 5; // 5%
$subtotal = WC()->cart->get_subtotal();
// Loop through the shipping taxes array
foreach ( $rates as $rate_key => $rate ){
$has_taxes = false;
// Targetting "flat rate"
if( 'local_pickup' === $rate->method_id ){
// Add the Percentage to the label name (otional
$rates[$rate_key]->label .= ' ( - ' . $percentage . '% )';
// Get the initial cost
$initial_cost = $new_cost = $rates[$rate_key]->cost;
// Calculate new cost
$new_cost = -$subtotal * $percentage / 100;
// 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;
$has_taxes = true; // Enabling tax
}
}
if( $has_taxes )
$rates[$rate_key]->taxes = $taxes;
}
}
return $rates;
}
代码位于活动子主题(或活动主题)的function.php文件中。经过测试和工作。
不要忘记在运输设置中禁用“启用调试模式”选项。