Change original cart price to change WooCommerce product

I tried to use this to change the original cart price, but not the cubes. I think this doesn't work because the product I am using is a variable product. The product ID is 141 and the change ID is 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

thank

+3


source to share


1 answer


You need to replace with $cart_item['product_id']

in order for it to work to change the product in your condition. $cart_item['variation_id']

This function only changes the display, but does not calculate:

// 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's a hooked function that will change the cart calculation with your price:

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

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

    foreach ( $cart_object->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+
            }
        }
    }
}

      



The code goes in the function.php file of your active child theme (or theme), as well as any plugin file.

So you get this:

enter image description here

This tested code works on Woocommerce 2.6.x and 3.0+

+2


source







All Articles