I am using the code below to calculate the prices for some specific products in certain categories and it works. the cart shows the corret value just like the checkout. The problem is in the mini-cart (if that is the correct name for the cart panel that shows up whenever i add a product in the cart.) I can see the correct price with the correct suffix that i have added and then the price returns back to its original. however in the cart page and the checkout page they are calculating the right way and it seems to work fine. Thank you for your help
add_action( 'woocommerce_before_calculate_totals', 'sv_change_product_price_cart', 10, 1 );
function sv_change_product_price_cart( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
foreach ( $cart->get_cart() as $cart_item ) {
$product = $cart_item['data'];
//check if is simple product
if( $product->is_type( 'simple' ) )
{
//check if is desired category
if ( has_term( array( 'tiles', 'tiles2' ), 'product_cat', $product->get_id() ) ) {
$product_id = $product->get_id();
$ppbox = get_post_meta( $product->get_id(), 'ppbox', true );
$product_price = $product->get_price();
$new_price=$ppbox*$product_price;
//$cart_item['data']->set_price( $new_price );
// WooCommerce versions compatibility
if ( version_compare( WC_VERSION, '3.0', '<' ) ) {
$cart_item['data']->price = $new_price; // Before WC 3.0
} else {
$cart_item['data']->set_price( $new_price ); // WC 3.0+
}
}
}
else
{ //if product has variations
//find parent id and use it to find parent category
$parent_id = $product->get_parent_id(); // The parent product ID
if ( has_term( array( 'tiles', 'tiles2' ), 'product_cat', $parent_id ) ) {
$ppbox = get_post_meta( $parent_id, 'ppbox', true ); //using parent id we find ppbox value
$product_price = $product->get_price();
$new_price=$ppbox*$product_price;
if ( version_compare( WC_VERSION, '3.0', '<' ) ) {
$cart_item['data']->price = $new_price; // Before WC 3.0
} else {
$cart_item['data']->set_price( $new_price ); // WC 3.0+
}
}
}
}
}
// Changing the displayed price (with custom label)
add_filter( 'woocommerce_cart_item_price', 'sv_display_product_price_cart', 100, 3 );
function sv_display_product_price_cart( $price, $cart_item, $cart_item_key ) {
$product = $cart_item['data'];
//check if is simple product
if( $product->is_type( 'simple' ) )
{
//check if is desired category
if ( has_term( array( 'tiles', 'tiles2' ), 'product_cat', $product->get_id() ) ) {
return wc_price($product->get_price())."/box";
}
}
else
{ //if product has variations
//find parent id and use it to find parent category
//$product = $cart_item->get_product();
$parent_id = $product->get_parent_id(); // The parent product ID
if ( has_term( array( 'tiles', 'tiles2' ), 'product_cat', $parent_id ) ) {
return wc_price($product->get_price())."/box";
}
}
return wc_price($product->get_price());
}