, ,

Update Woocommerce cart price with code

Woocommerce-update-cart-price

How to update/override woocommerce cart price with code

Use the woocommerce_cart_calculate_fees hook to update the woocommerce cart price.

add_action( 'woocommerce_cart_calculate_fees', 'cp_add_custom_price' );

In the function get product details and update with your new price like below.

function cp_add_custom_price( $cart_object ) {
	global $woocommerce;
	foreach ( $cart_object->cart_contents as $key => $value ) {
		//Get the product data like below
		$proid = $value['product_id'];
		$variantid = $value['variation_id'];
		$price = $value['data']->price;
		//check your condition
		if($youcondition == true ) {
			//update with the new price
			$value['data']->price = $newprice;
		}
	}
}

To add an extra fees to woocommerce cart use the add_fee() function in the same hook like below.

$excost = 5.99;
$woocommerce->cart->add_fee( 'Express delivery', $excost, true, 'standard' );

This is working example to add a special fee for products from category with id 10

function cp_add_custom_price( $cart_object ) {

    global $woocommerce;
	$specialfeecat = 10; // category id for the special fee
	$spfee = 0.00; // initialize special fee
	$spfeeperprod = 5.00; //special fee per product
 	
    foreach ( $cart_object->cart_contents as $key => $value ) {
        
        $proid = $value['product_id']; //get the product id from cart
		$quantiy = $value['quantity']; //get quantity from cart

		$terms = get_the_terms( $proid, 'product_cat' ); //get taxonamy of the prducts
		if ( $terms && ! is_wp_error( $terms ) ) :
 			foreach ( $terms as $term ) {
				$catid = $term->term_id;
				if($specialfeecat == $catid ) {
					$spfee = $spfee + $quantiy * $spfeeperprod;
				}
			}
		endif;	
    }

	if($spfee > 0 ) {
	
		$woocommerce->cart->add_fee( 'Special fee', $spfee, true, 'standard' );
	}
	
}

add_action( 'woocommerce_cart_calculate_fees', 'cp_add_custom_price' );