update price before added to cart woocommerce code example

Example: woocommerce update cart price

function before_calculate_totals( $cart_obj ) {
 if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
  return;
 }
 // Iterate through each cart item
 foreach( $cart_obj->get_cart() as $key=>$value ) {  
   if( isset( $value['csCost'] ) ) {
    $getPrice = $value['data']->get_price();
     $price = $value['csCost'] + $getPrice;
     $value['data']->set_price( ( $price ) );
   }
   if( isset( $value['setCost'] ) ) {
    $getPrice = $value['data']->get_price();
     $price = $value['setCost'] + $getPrice;
     $value['data']->set_price( ( $price ) );
   }
  
 }
}
add_action( 'woocommerce_before_calculate_totals', 'before_calculate_totals', 10, 1 );

Tags:

C Example