Reputation: 431
I tried using this to change the original price in the cart but no dice. I think it's not working because the product I'm using is a variable product. The Product ID is 141 and the variation 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 );
How to make it work
Thanks
Upvotes: 3
Views: 2927
Reputation: 253901
You should need to replace $cart_item['product_id']
by $cart_item['variation_id']
to make it working for a product variation in your condition.
This function will only change the display, but not the calculation:
// 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;
}
Here is the hooked function that will change the cart calculation with your 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+
}
}
}
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
So you will get that:
This code is tested ad works on Woocommerce version 2.6.x and 3.0+
Upvotes: 3