首页 > 解决方案 > 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 个都没有,则不需要显示总订单节省。

有人可以帮我实现这一目标吗?

标签: phpwordpresswoocommercepricediscount

解决方案


请尝试以下方法,这将解决您的问题并处理显示税收设置:

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 文件中。测试和工作。


推荐阅读