Change cart item prices based on custom cart item data in Woocommerce

Change cart item prices in WooCommerce code

We need to use 2 different hooks:

  • The first one just as yours without trying to change the price in it.
  • The second one where you will change your cart item price.

The code:

<?php
  add_filter( 'woocommerce_add_cart_item', 'add_custom_cart_item_data', 10, 2 );

  function add_custom_cart_item_data( $cart_item_data, $cart_item_key ) {

      if( isset( $_POST['new-width'] ) )
          $cart_item_data['new-width'] = $_POST['new-width'];
      if(isset( $_POST['new-height'] ) )
         $cart_item_data['new-height'] = $_POST['new-height'];

      return $cart_item_data;
  }


  add_action( 'woocommerce_before_calculate_totals', 'set_custom_cart_item_price', 20, 1 );

  function set_custom_cart_item_price( $cart ) {
      if ( is_admin() && ! defined( 'DOING_AJAX' ) )
          return;

      if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
          return;

      // First loop to check if product 11 is in cart
      foreach ( $cart->get_cart() as $cart_item ){
          if( isset($cart_item['new-width']) && isset($cart_item['new-height']) 
          && ! empty($cart_item['new-width']) && ! empty($cart_item['new-height']) )
              $cart_item['data']->set_price( '30' );
      }
  }
?>

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Was this article helpful?
YesNo

Leave a comment

Your email address will not be published. Required fields are marked *