我想显示适用于 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 不会提供该功能......
如果您查看购物车商品数据,该功能就存在。
要在购物车页面显示应用于每个购物车商品的折扣金额(单个产品价格),请使用以下命令:
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">(- %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">(- %s)</span>'), wc_price($item_subtotal - $item_total) );
}
return $item_subtotal_html;
}
代码位于主题的functions.php 文件中(或插件中)。已测试并有效。