在 在 Woocommerce 中根据客户送货区域显示自定义消息答案中,我找到了一种根据送货区域在购物车中显示消息的解决方案。
我想根据送货区域显示一条消息,并且仅当购物车数量小于特定数量时才显示,例如:
这是我尝试自己编辑PHP代码的:
add_action( 'woocommerce_cart_totals_after_shipping', 'shipping_notice_displayed', 20 );
add_action( 'woocommerce_review_order_after_shipping', 'shipping_notice_displayed', 20 );
function shipping_notice_displayed() {
if ( did_action( 'woocommerce_cart_totals_after_shipping' ) >= 2 ||
did_action( 'woocommerce_review_order_after_shipping' ) >= 2 ) {
return;
}
// Chosen Shipping Method
$chosen_shipping_zone_id = WC()->session->get( 'chosen_shipping_methods' )[0];
$chosen_shipping_zone = explode(':', $chosen_shipping_method_id)[0];
$cart_subtotal = WC()->cart->subtotal;
// Settings
$cart_maximum1 = 29;
$cart_maximum2 = 49;
// HERE define the cart maximum
if ( $cart_subtotal < $cart_maximum2 && $chosen_shipping_zone != 'Shipping Zone I' ) {
$cart_maximum = $cart_maximum1;
} elseif ( $cart_subtotal < $cart_maximum2 && $chosen_shipping_method == 'Shipping Zone I' ) {
$cart_maximum = $cart_maximum2;
}
// Display a message
if( isset($cart_maximum) ){
// The message
$message = sprintf( 'Above 29,00 € cart total save 5 €!' ,
is_cart() ? 'Maximum' : 'Max',
strip_tags( wc_price( $cart_maximum, array('decimals' => 2 ) ) )
);
// Display
echo '</tr><tr class="shipping info"><th> </th><td data-title="Delivery info">'.$message.'</td>';
}
}
但是出现一些错误,我的代码不起作用。如何根据运送区域和最大购物车小计显示不同的购物车消息?
您的代码中存在一些错误和缺失的内容,请尝试以下操作,以根据运输区域和阈值购物车数量显示动态购物车消息:
add_action( 'woocommerce_cart_totals_after_shipping' , 'shipping_zone_message_based_on_cart_amount' );
add_action( 'woocommerce_review_order_after_shipping' , 'shipping_zone_message_based_on_cart_amount' );
function shipping_zone_message_based_on_cart_amount() {
// HERE in the array, define the shipping zone name with threshold max amount (pairs)
$zone_name_threshold = array(
'Shipping Zone 1' => 29,
'Shipping Zone 2' => 49,
);
// Get the customer shipping zone name
$chosen_method = WC()->session->get( 'chosen_shipping_methods' ); // The chosen shipping mehod
$instance_id = end( explode(':', reset($chosen_method) ) );
$shipping_zone = WC_Shipping_Zones::get_zone_by( 'instance_id', $instance_id );
$zone_name = $shipping_zone->get_zone_name();
if( isset($zone_name_threshold[$zone_name]) && WC()->cart->subtotal < $zone_name_threshold[$zone_name]){
echo '</tr>
<tr class="shipping-info">
<th> </th>
<td data-title="Delivery info">' . sprintf(
__( "Above %s cart amount, save 5 €!", "woocommerce"), wc_price($zone_name_threshold[$zone_name])
) . '</td>';
}
}
代码位于子主题的functions.php 文件中(或插件中)。已测试并有效。