0
votes

I'm using the following code for dynamic pricing on WooCommerce products:

function add_cart_item_data( $cart_item_data, $product_id, $variation_id ) {
    if( ! empty( $_POST['custom-total-price'] ) ) {
        $product = wc_get_product( $product_id );
        $price = $product->get_price();
        $cart_item_data['custom_price'] = $_POST['custom-total-price'];
    }
    return $cart_item_data;
}
add_filter( 'woocommerce_add_cart_item_data', 'add_cart_item_data', 10, 3 );

function before_calculate_totals( $cart_obj ) {
  if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
    return;
  }
  foreach( $cart_obj->get_cart() as $key=>$value ) {
    if( isset( $value['custom_price'] ) ) {
      $price = $value['custom_price'];
      $value['data']->set_price( ( $price ) );
    }
  }
}
add_action( 'woocommerce_before_calculate_totals', 'before_calculate_totals', 10, 1 );

The price is calculated with jQuery on the front end and sent through a form input when the product is added to the cart.

This is working in the sense that the cart total is updated, and the custom price for individual items is shown on the cart page. However, it's still showing a price of 0 in the mini cart. Any idea how I can show the custom price in the mini cart?

1
Why are you doing these calculations custom? You may run into problems when persisting into the db... Anyway, you will have to set a hook for the Minicart to and update the price there, but unless you want to call a resource everytime you load a page where the mini cart is displayed, you would have to take the prices server-sideRobert Vlasiu
Backend/PHP is not my strong point, so the code I'm using above is just what I've found from googling.Ash
@VlasiuRobert Do you mind sharing the code for the hook/price update?Ash

1 Answers

0
votes
add_filter( 'woocommerce_cart_item_price', 'woocommerce_cart_item_price_filter', 10, 3 );

function woocommerce_cart_item_price_filter( $price, $cart_item, $cart_item_key ) {
    /*
       calculate price
      */

    return $yourPrice;
}

I hope this helps you