代码之家  ›  专栏  ›  技术社区  ›  Mairyu

如何在购物车中显示适用于每种商品的优惠券/折扣部分(Woocommerce)

  •  0
  • Mairyu  · 技术社区  · 3 年前

    我想在WooCommerce中显示每个购物车项目的折扣金额。我查看了WooCommerce类/函数页面,似乎找不到匹配的页面。他们似乎唯一提供的是购物车的总折扣,我目前正在这样使用:

    $OrderSummarySubtotal = WC()->cart->get_subtotal(); // -> 600
    
    $CartTotalDiscount = WC()->cart->get_cart_discount_total(); // -> 60
    
    $CartTotal = WC()->cart->get_cart_contents_total(); // -> 540
    

    那么60是如何计算的呢?(即如何将它们分配给每种产品)

    我想我可以手动计算折扣,但这很繁琐,容易出现舍入错误等,不想造成任何混乱。

    令人惊讶的是WooCommerce不会提供这种功能。。。

    0 回复  |  直到 3 年前
        1
  •  3
  •   LoicTheAztec    3 年前

    如果您查看购物车项目数据,则存在该功能。

    要在购物车页面中显示应用于每个购物车项目的折扣金额(单个产品价格),请使用以下内容:

    add_filter( 'woocommerce_cart_item_price', 'cart_item_discount_amount_suffix', 100, 2 ); 
    function cart_item_discount_amount_suffix( $item_price_html, $cart_item ) { 
        if( count( WC()->cart->get_applied_coupons() ) > 0 ) {
            $item_subtotal = $cart_item['line_subtotal'];
            $item_total    = $cart_item['line_total'];
    
            if ( $cart_item['data']->is_taxable() &&  WC()->cart->display_prices_including_tax() ) {
                $item_subtotal += $cart_item['line_subtotal_tax'];
                $item_total    += $cart_item['line_tax'];
            }
            $item_price = $item_subtotal / $cart_item['quantity'];
            $item_price_discounted = $item_total / $cart_item['quantity'];
            $item_price_html .= sprintf( ' <span class="discount-amount">(-&nbsp;%s)</span>', wc_price($item_price - $item_price_discounted) );
        }
        return $item_price_html;
    }
    

    显示应用于每个购物车项目的折扣金额 小计 ,在购物车页面中 和在签出页面中 ,请使用以下内容:

    add_filter( 'woocommerce_cart_item_subtotal', 'cart_item_subtotal_discount_amount_suffix', 100, 2 ); 
    function cart_item_subtotal_discount_amount_suffix( $item_subtotal_html, $cart_item ) { 
        if( count( WC()->cart->get_applied_coupons() ) > 0 ) {
            $item_subtotal = $cart_item['line_subtotal'];
            $item_total    = $cart_item['line_total'];
    
            if ( $cart_item['data']->is_taxable() &&  WC()->cart->display_prices_including_tax() ) {
                $item_subtotal += $cart_item['line_subtotal_tax'];
                $item_total    += $cart_item['line_tax'];
            }
            $item_subtotal_html .= sprintf( ' <span class="discount-amount">(-&nbsp;%s)</span>', wc_price($item_subtotal - $item_total) );
        }
        return $item_subtotal_html;
    }
    

    代码位于主题的functions.php文件中(或插件中)。已测试并工作。