我想展示一下适用于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">(-&nbsp;%s)</span>', wc_price($item_price - $item_price_discounted) );
    }
    return $item_price_html;
}

要在购物车页面and in checkout page中显示应用于每个购物车项目subtotal的折扣金额,请使用以下内容:

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;
}

代码放在主题的unctions.php文件中(或在插件中).经过测试,效果良好.

Php相关问答推荐

WooCommerce拆分运输包裹上的商品数量增加运输成本

try 修改这个PHP代码如果语句在WordPress""

LaravelEloquent 地根据表中的值提取记录

WooCommerce/WordPress:简单的产品属性显示

Laveel Livewire Get Groupby姓名列表

如何在php中生成包含第100秒的时间序列?

使用PHP编码的字符串与使用OpenSSL编写的shell 代码之间的差异

当配置的URL为空时禁用Laravel Slack日志(log)记录

Laravel 10中的Validator类

对 WooCommerce 购物车和 checkout 中显示的运输方式进行排序

PHP 中使用 JSON 的自定义会话处理程序会因错误而 destruct 会话

PHP 解析 XML 以获取多个深度的所有字符串值

带有分类术语数组的 WordPress Elementor 自定义查询 - 如何要求所有术语都在返回的帖子中

PHP 创建 CSV 文件并用波斯语写入

在WooCommerce我的账户单个订单页面中添加订单商品部分和按钮

PHP:如何将多列sql查询结果转换成数组

自定义主键值未正确显示

Shopware 6:无法在新的自定义插件中保存关联字段(媒体)

Laravel 响应 html 默认页面忽略控制器

用于多态服务的 Symfony setter 注入