在购物车中更改WooCommerce产品差异的原始价格

时间:2017-05-12 17:26:02

标签: php wordpress woocommerce cart product

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

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

如何使其发挥作用

由于

1 个答案:

答案 0 :(得分:2)

您应该使用 $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 = '$50.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文件中,或者放在任何插件文件中。

所以你会得到它:

enter image description here

此代码经过测试,适用于Woocommerce版本2.6.x和3.0 +