I want to change the regular price of the variable product by the calculated price but i’m able to change price only for simple product and my code is not working for variable product. Anyone please guide me to do it properly so its work for every type of product.Thanks
add_filter( 'woocommerce_add_cart_item_data', 'save_custom_data_in_cart_object', 30, 3 );
function save_custom_data_in_cart_object( $cart_item_data, $product_id, $variation_id ) {
if( ! isset( $_POST['custom_text'] ) || empty( $_POST['custom_text'] ) && ! isset( $_POST['product_custom_price'] ) || empty( $_POST['product_custom_price'] ) )
return $cart_item_data;
// Get an instance of the WC_Product object
$product = $variation_id > 0 ? wc_get_product($variation_id) : wc_get_product($product_id);
$product_price = (float) $product->get_price(); // Get the product price
// Get the text
$custom_text = sanitize_text_field ( $_POST['custom_text'] );
$product_custom_price = sanitize_text_field ( $_POST['product_custom_price'] );
$cart_item_data['custom_data']['price'] = $product_custom_price * $custom_text ;
$cart_item_data['custom_data']['text'] = $custom_text;
// $cart_item_data['custom_data']['custom_price'] = $product_custom_price;
if(!empty($custom_text) && !empty($product_custom_price)){
echo "we filled with joyyyy:)";
$multiplyPrice = $cart_item_data['custom_data']['price'];
$regular_price = $multiplyPrice;
$productID = $product_id;
$product = wc_get_product($productID);
// Set regular price
$product->set_regular_price( $regular_price );
// If your product has a Sale price
$new_price = $regular_price;
// Set new price
$product->set_price( $new_price );
// Save to database (Note: You might want to clear cache of your page and then reload, if it still doesn't show up go to the product page and check there.)
$product->save();
}
return $cart_item_data;
}