更改 WooCommerce 产品变体的购物车原价

Change original price in cart for WooCommerce product variation

我尝试使用它来更改购物车中的原始价格,但没有骰子。我认为它不起作用,因为我使用的产品是可变产品。产品 ID 为 141,变体 ID 为 142。

function sv_change_product_price_cart( $price, $cart_item, $cart_item_key ) {
    if ( 142 === $cart_item['product_id'] ) {
        $price = '.00 per Unit<br>(7-8 skewers per Unit)';
    }
    return $price;
}
add_filter( 'woocommerce_cart_item_price', 'sv_change_product_price_cart', 10, 3 );

如何让它发挥作用

谢谢

您应该需要将 $cart_item['product_id'] 替换为 $cart_item['variation_id'] 以使其适用于您条件下的产品变体。

这个函数只会改变显示,不会改变计算:

// Changing the displayed price (with custom label)
add_filter( 'woocommerce_cart_item_price', 'sv_display_product_price_cart', 10, 3 );
function sv_display_product_price_cart( $price, $cart_item, $cart_item_key ) {
    if ( 142 == $cart_item['variation_id'] ) {
        // Displaying price with label
        $price = '.00 per Unit<br>(7-8 skewers per Unit)';
    }
    return $price;
}

这是一个钩子函数,它将根据您的价格更改购物车计算:

// Changing the price (for cart calculation)
add_action( 'woocommerce_before_calculate_totals', 'sv_change_product_price_cart', 10, 1 );
function sv_change_product_price_cart( $cart ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    foreach ( $cart->get_cart() as $cart_item ) {
        if ( 142 == $cart_item['variation_id'] ){
            // Set your price
            $price = 50;

            // WooCommerce versions compatibility
            if ( version_compare( WC_VERSION, '3.0', '<' ) ) {
                $cart_item['data']->price = $price; // Before WC 3.0
            } else {
                $cart_item['data']->set_price( $price ); // WC 3.0+
            }
        }
    }
}

代码进入您的活动子主题(或主题)的 function.php 文件或任何插件文件。

所以你会得到:

此代码经过测试,广告适用于 Woocommerce 版本 2。6.x 和 3.0+