settings = $settings;
$this->hooks();
}
protected function hooks() {
// Calculate product price in cart by pricing rules
add_action( 'woocommerce_before_calculate_totals', [ $this, 'calculateTotals' ], 10, 3 );
add_action( 'woocommerce_before_mini_cart_contents', [ $this, 'miniCartSubTotal' ], 10, 3 );
add_filter( 'woocommerce_cart_item_price', [ $this, 'calculateItemPrice' ], 10, 2 );
}
/**
* Calculate price by quantity rules
*
* @param WC_Cart $cart
*/
public function calculateTotals( $cart ) {
if ( ! empty( $cart->cart_contents ) ) {
foreach ( $cart->cart_contents as $key => $cart_item ) {
if ( $cart_item['data'] instanceof WC_Product ) {
$product_id = ! empty( $cart_item['variation_id'] ) ? $cart_item['variation_id'] : $cart_item['product_id'];
$new_price = PriceManager::getPriceByRules( $cart_item['quantity'], $product_id );
if ( $new_price !== false ) {
$cart_item['data']->set_price( $new_price );
}
}
}
}
}
public function miniCartSubTotal() {
$cart = wc()->cart;
$cart->calculate_totals();
}
/**
* Calculate price in mini cart
*
* @param string $price
* @param array $cart_item
*
* @return string
*/
public function calculateItemPrice( $price, $cart_item ) {
if ( $cart_item['data'] instanceof WC_Product ) {
$new_price = PriceManager::getPriceByRules( $cart_item['quantity'], $cart_item['data']->get_id() );
// To get real product price
$product = wc_get_product( $cart_item['data']->get_id() );
if ( $new_price !== false ) {
if ( $this->settings->getAll()['show_discount_in_cart'] === 'yes' && tpt_fs()->can_use_premium_code() ) {
return ' ' . wc_price( $product->get_price() ) . ' ' . wc_price( $new_price ) . ' ';
}
return wc_price( $new_price );
}
}
return $price;
}
}