Ash
Ash

Reputation: 49

WooCommerce - Show custom price in mini cart

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?

Upvotes: 1

Views: 1122

Answers (1)

Robert Vlasiu
Robert Vlasiu

Reputation: 402

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

Upvotes: 0

Related Questions