首页 > 解决方案 > 计算并显示购物车中的存款总额和结帐总额

问题描述

我有一个 WooCommerce 网上商店,里面有来自世界各地的不同种类的啤酒。如果您退回一个空瓶子,您将获得 0,10 或类似的押金。我创建了一个 ACF(高级自定义字段),可以在其中添加空瓶子的押金价格。我设法将其添加到我的购物车页面,并将其显示在一瓶的单一价格(0,10)下,如果有更多瓶子(0,40),则显示在小计下。

这是在购物车和结帐中工作的,但如果您将瓶子退回商店,我想从总存款中扣除一笔款项。

如何创建一个函数来计算购物车中所有有存款的瓶子的总和?

我设法获得了第一个使用此功能的 this:

add_filter( 'woocommerce_cart_item_price', 'add_deposit_value_to_cart_single' , 10, 3 );
add_filter( 'woocommerce_cart_item_subtotal', 'add_deposit_value_to_cart_total', 10, 3 );


/**
* Statiegeld toevoegen onder single prijs product winkelwagen
*/
function add_deposit_value_to_cart_single( $product_price, $values ) {
    $statiegeld = get_field( "statiegeld", $values['product_id']);
    $dep_total = $statiegeld;
    
    if( ! empty( $dep_total ) )
        return $product_price . '<br /><small class="deposit_label">' .  sprintf( __( 'statiegeld %s' ), wc_price( $dep_total ) ) . '</small>';
    
    return $product_price;
}

/**
* Statiegeld toevoegen aan subtotaal in winkelwagen
*/
function add_deposit_value_to_cart_total( $product_price, $values ) {
    $statiegeld = get_field( "statiegeld", $values['product_id']);
    $dep_total = $statiegeld * $values['quantity'];
    
    if( ! empty( $dep_total ) )
        
        return $product_price . '<br /><small class="deposit_label">' .  sprintf( __( 'statiegeld totaal %s' ), wc_price( $dep_total ) ) . '</small>';
    
    return $product_price;
}

如果有人有一个想法,我非常感激,因为我无法弄清楚。

标签: phpfunctionwoocommerce

解决方案


两个函数的参数都有一些错误。

尝试这个:

/**
* Statiegeld toevoegen onder single prijs product winkelwagen
*/
add_filter( 'woocommerce_cart_item_price', 'add_deposit_value_to_cart_single' , 10, 3 );
function add_deposit_value_to_cart_single( $price, $cart_item, $cart_item_key ) {
    $statiegeld = get_field( "statiegeld", $cart_item['product_id']);
    $dep_total = $statiegeld;
    
    if( ! empty( $dep_total ) )
        return $price . '<br /><small class="deposit_label">' .  sprintf( __( 'statiegeld %s' ), wc_price( $dep_total ) ) . '</small>';
    
    return $price;
}

/**
* Statiegeld toevoegen aan subtotaal in winkelwagen
*/
add_filter( 'woocommerce_cart_item_subtotal', 'add_deposit_value_to_cart_total', 10, 3 );
function add_deposit_value_to_cart_total( $price, $cart_item, $cart_item_key ) {
    $statiegeld = get_field( "statiegeld", $cart_item['product_id']);
    $dep_total = $statiegeld * $cart_item['quantity'];

    if ( ! empty( $dep_total ) ) {
        return $price . '<br /><small class="deposit_label">' .  sprintf( __( 'statiegeld totaal %s' ), wc_price( $dep_total ) ) . '</small>';
    }

    return $price;
}

我已经测试了代码,它工作正常。结果如下:

在此处输入图像描述


推荐阅读