如何解决基于权重的渐进式折扣显示剩余重量,以获得更好的折扣信息
我正在使用Apply a progressive discount based onWoocommerce cart total weight答案代码(针对我的上一个问题),以根据购物车总重量来增加批量折扣。
该代码是完美的,但我想在购物车页面(仅购物车)上方显示横幅,例如“已添加到购物车”消息,该消息显示了一条消息,以及客户必须为下一个折扣规则订购的金额更多
示例消息:“如果您订购10欧元,则您将获得10%的折扣”
我试图为消息框找到正确的代码,但找不到正确的代码。我只能找到wc_add_to_cart_message_html
,但是我很确定这不是正确的选择。
很抱歉所有这些问题,但是我对PHP还是很陌生,想学习。 希望任何人都能提供帮助。
解决方法
已更新
您将必须用以下代码替换所有相关代码,这些代码将根据购物车的重量进行折扣,并显示一条定制消息,显示剩余的重量以获得更好的百分比折扣(显示的百分比)。
消息提示:由于这是基于重量的折扣,因此无法显示剩余费用。相反,您可以显示剩余的重量以获得更好的折扣。
代码如下:
add_action( 'woocommerce_cart_calculate_fees','shipping_weight_discount',30,1 );
function shipping_weight_discount( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$cart_weight = $cart->get_cart_contents_weight();
$cart_subtotal = $cart->get_subtotal(); // Or $cart->subtotal;
$percentage = 0;
if ( $cart_weight >= 10 && $cart_weight < 30 )
{
$percentage = 5;
$remaining_weight = 30 - $cart_weight;
$next_percent = 7.5;
}
elseif ( $cart_weight >= 30 && $cart_weight < 70 )
{
$percentage = 7.5;
$remaining_weight = 70 - $cart_weight;
$next_percent = 10;
}
elseif ( $cart_weight >= 70 && $cart_weight < 130 )
{
$percentage = 10;
$remaining_weight = 130 - $cart_weight;
$next_percent = 12.5;
}
elseif ( $cart_weight >= 130 && $cart_weight < 200 ) {
$percentage = 12.5;
$remaining_weight = 200 - $cart_weight;
$next_percent = 15;
}
elseif ( $cart_weight >= 200 )
{
$percentage = 15;
$next_percent = false;
}
else
{
$next_percent = 5;
$remaining_weight = 10 - $cart_weight;
}
// Apply a calculated discount based on weight
if( $percentage > 0 ) {
$discount = $cart_subtotal * $percentage / 100;
$cart->add_fee( sprintf( __( 'Weight %s discount','woocommerce' ),$percentage.'%'),-$discount );
}
if ( did_action( 'woocommerce_cart_calculate_fees' ) >= 2 )
return;
// Display a custom message
if ( is_cart() && $next_percent ) {
wc_add_notice( sprintf(
__("If you order for %s extra,you will receive a %s discount.","woocommerce"),wc_format_weight($remaining_weight),$next_percent.'%'
),'notice' );
}
}
代码进入活动子主题(或活动主题)的function.php文件。经过测试,可以正常工作。
购物车中显示的消息的屏幕截图: