php - WooCommerce Checkout 中的自定义总储蓄金额显示问题
问题描述
我正在使用此代码片段在 WooCommerce 结帐时显示总订单节省:
add_action( 'woocommerce_review_order_after_order_total', 'show_total_discount_cart_checkout', 9999 );
function show_total_discount_cart_checkout() {
$discount_total = 0;
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$product = $values['data'];
if ( $product->is_on_sale() ) {
$regular_price = $product->get_regular_price();
$sale_price = $product->get_sale_price();
$discount = ( $regular_price - $sale_price ) * $values['quantity'];
$discount_total += $discount;
}
}
if ( $discount_total > 0 ) {
echo '<tr class="total-saved"><th>You Saved</th><td data-title="You Saved">' . wc_price( $discount_total + WC()->cart->get_discount_total() ) .'</td></tr>';
}
}
它应该显示客户节省的总金额(销售价格加上优惠券折扣)。截图:https ://ibb.co/KXg2bDj
但是,如果购物车中没有打折产品,则不会显示订单节省的总金额,即使订单上有优惠券代码也是如此。仅当购物车中有打折产品时,才会显示总订单节省。截图:https ://ibb.co/PCQPGZx
如果有优惠券代码应用于订单,如果购物车中有打折产品或两者都有,我希望显示订单节省的总金额。如果这 2 个都没有,则不需要显示总订单节省。
有人可以帮我实现这一目标吗?
解决方案
请尝试以下方法,这将解决您的问题并处理显示税收设置:
add_action( 'woocommerce_review_order_after_order_total', 'show_total_discount_cart_checkout', 1000 );
function show_total_discount_cart_checkout() {
$discount_total = 0; // Initializing
// Loop through cart items
foreach ( WC()->cart->get_cart() as $item ) {
$product = $item['data'];
if ( $product->is_on_sale() ) {
$regular_args = array( 'price' => $product->get_regular_price() );
if ( WC()->cart->display_prices_including_tax() ) {
$active_price = wc_get_price_including_tax( $product );
$regular_price = wc_get_price_including_tax( $product, $regular_args );
} else {
$active_price = wc_get_price_excluding_tax( $product );
$regular_price = wc_get_price_excluding_tax( $product, $regular_args );
}
$discount_total += ( $regular_price - $active_price ) * $item['quantity'];
}
}
if ( WC()->cart->display_prices_including_tax() ) {
$discount_total += WC()->cart->get_discount_tax();
}
$discount_total += WC()->cart->get_discount_total();
if ( $discount_total > 0 ) {
$text = __("You Saved", "woocommerce");
printf( '<tr class="total-saved"><th>%s</th><td data-title="%s">%s</td></tr>', $text, $text, wc_price($discount_total) );
}
}
代码位于活动子主题(或活动主题)的 functions.php 文件中。测试和工作。
推荐阅读
- java - TypeNotPresentException , Maven 项目构建生命周期映射问题 执行 maven 构建时出现异常
- reactjs - ReactJS + Docker-Compose 错误 | “找不到所需的文件”
- javascript - 如何将此日期转换为实际日期
- reactjs - _this2.setState 不是反应异步的功能
- python - 如何在字典/列表数据结构的“级别”插入?- { 'foo': 'bar', 'more': [ { 'foo': 无 } ] }
- java - 如何在 JSP 中迭代 ArrayList
- java - 如何显示来自firebase的所有子数据但排除recycleview中的特定子数据?
- android - Android Studio 4.1 Canary 1 未显示 Layout Inspector 实时更新
- java - 明智地打印树级别
- typescript - TypeScript - 为类属性设置默认值和可用值