在WooCommerce中仅根据产品重量更改购物车小计

时间:2020-02-16 20:13:50

标签: php wordpress woocommerce cart hook-woocommerce

我一直在尝试执行计算后更新购物车总数。

add_action( 'woocommerce_before_calculate_totals', 'set_cart_item_calculated_price', 10, 1 );
function set_cart_item_calculated_price( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Required since Woocommerce version 3.2 for cart items properties changes
    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // Loop through cart items
    foreach ( $cart->get_cart() as $cart_item ) {
        // Set the new calculated price based on lenght
        if( isset($cart_item['data']) ) {
            $cart_item['data']->set_price( $cart_item['data']->get_price() * $cart_item['data']->get_weight() );
        }
    }
}

它工作正常,但是它更改了我不想要的正常产品价格


此钩子不会改变产品价格,但不会更新购物车总额:

add_filter('woocommerce_cart_product_subtotal', 'filter_woocommerce_cart_product_subtotal', 10, 4);
function filter_woocommerce_cart_product_subtotal($product_subtotal, $product, $quantity, $cart) {
    $new_subtotal = $product_subtotal;
    $weight = $product->get_weight();
    $price = $product->get_price();
    if($weight && $price){
        $new_subtotal = ($price * (float)$weight) * $quantity;
    }
    return wc_price($new_subtotal);
}

如何根据产品重量仅更改每个购物车小计?任何帮助表示赞赏。

0 个答案:

没有答案