【发布时间】:2018-12-12 18:40:42
【问题描述】:
我有一个使用 WooCommerce 插件的 WordPress 网站。如果买家选择本地取货作为送货方式,我愿意为买家提供购物车总额 5% 的折扣。
我已经尝试过 - 5 * [qty],但它似乎不起作用。
我也试过 -0.95 * [成本] 没有运气
【问题讨论】:
标签: php wordpress woocommerce shipping discount
我有一个使用 WooCommerce 插件的 WordPress 网站。如果买家选择本地取货作为送货方式,我愿意为买家提供购物车总额 5% 的折扣。
我已经尝试过 - 5 * [qty],但它似乎不起作用。
我也试过 -0.95 * [成本] 没有运气
【问题讨论】:
标签: php wordpress woocommerce shipping discount
我正在使用 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' ) ) {
// Define the discount percentage
$discount = $cart->subtotal * 0.05;
// Add your discount note to cart
$cart->add_fee( __( 'Collection discount applied', 'yourtext-domain' ) , -$discount );
}
}
add_action( 'woocommerce_cart_calculate_fees', 'prefix_add_discount_line');
【讨论】:
$cart->add_fee( __( 'Collection discount applied', 'yourtext-domain' ) , -$discount, true );
fee 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 文件中。经过测试并且可以工作。
别忘了在发货设置中禁用“启用调试模式”选项。
【讨论】: