1

在我们的woocommerce商店中,客户可以输入产品的自定义宽度和高度以及根据此详细信息计算的产品价格。

例如,如果产品的初始价格是 50。客户加上width =2, height=3,那么这个产品的价格是50*2*3=300

为此,我们使用以下代码

// Save custom field value in cart item as custom data
add_filter( 'woocommerce_add_cart_item', 'calculate_custom_cart_item_prices', 30, 3 );
function calculate_custom_cart_item_prices( $cart_item_data, $product_id, $variation_id ) {
    if ( isset($_POST['width']) && isset($_POST['height']) ) {
        // Get the correct Id to be used (compatible with product variations)
        $the_id = $variation_id > 0 ? $variation_id : $product_id;

        $product = wc_get_product( $the_id ); // Get the WC_Product object
        $product_price = (float) $product->get_price(); // Get the product price

        // Get the posted data
        $width  = (float) sanitize_text_field( $_POST['width'] );
        $height = (float) sanitize_text_field( $_POST['height'] );

        $new_price = $width * $height * $product_price; // Calculated price

        $cart_item_data['calculated-price'] = $new_price; // Save this price as custom data
    }
    return $cart_item_data;
}

// Set custom calculated price in cart item price
add_action( 'woocommerce_before_calculate_totals', 'set_calculated_cart_item_price', 20, 1 );
function set_calculated_cart_item_price( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Loop through cart items
    foreach ( $cart->get_cart() as $cart_item ){
        if( ! empty( $cart_item['calculated-price'] ) ){
            // Set the calculated item price (if there is one)
            $cart_item['data']->set_price( $cart_item['calculated-price'] );
        }
    }

它是 wormking ,但问题是:

当客户为此产品申请 50% 优惠券代码时,折扣为 25 ,因为它基于 50*(50/100)=25 计算;

但实际上产品新价是300,所以折扣应该是300*(50/100)=150;

4

1 回答 1

1

尝试将您的 'calculate_custom_cart_item_prices' 函数更新为类似的内容,看看是否有帮助。

add_filter( 'woocommerce_add_cart_item', 'calculate_custom_cart_item_prices', 30, 2 );
function calculate_custom_cart_item_prices( $cart_item_data, $cart_item_key ) {
    if ( isset($_POST['width']) && isset($_POST['height']) ) {
        // Get the correct Id to be used (compatible with product variations)
        $the_id = $cart_item_data['variation_id'] > 0 ? $cart_item_data['variation_id'] : $cart_item_data['product_id'];

        $product = wc_get_product( $the_id ); // Get the WC_Product object
        $product_price = (float) $product->get_price(); // Get the product price

        // Get the posted data
        $width  = (float) sanitize_text_field( $_POST['width'] );
        $height = (float) sanitize_text_field( $_POST['height'] );

        $new_price = $width * $height * $product_price; // Calculated price

        $cart_item_data['calculated-price'] = $new_price; // Save this price as custom data
    }
    return $cart_item_data;
}

我对正在发生的事情的猜测是 Woocommerce 的变化改变了“woocommerce_add_cart_item”过滤器的工作方式,因此您需要更新此功能。

于 2018-03-22T21:37:40.210 回答