Step 1:- You need to create some custom hidden fields to send custom data that will show on single product page. for example :-
add_action('woocommerce_before_add_to_cart_button', 'custom_data_hidden_fields');
function custom_data_hidden_fields() {
echo '<div class="imput_fields custom-imput-fields">
<label class="price_prod">price: <br><input type="text" id="price_prod" name="price_prod" value="" /></label>
<label class="quantity_prod">quantity: <br>
<select name="quantity_prod" id="quantity_prod">
<option value="1" selected="selected">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
</label>
</div><br>';
}
Step 2:- Now after done that you need to write the main logic for Save all Products custom fields to your cart item data, follow the below codes.
// Logic to Save products custom fields values into the cart item data
add_action( 'woocommerce_add_cart_item_data', 'save_custom_data_hidden_fields', 10, 2 );
function save_custom_data_hidden_fields( $cart_item_data, $product_id ) {
$data = array();
if( isset( $_REQUEST['price_prod'] ) ) {
$cart_item_data['custom_data']['price_pro'] = $_REQUEST['price_prod'];
$data['price_pro'] = $_REQUEST['price_prod'];
}
if( isset( $_REQUEST['quantity_prod'] ) ) {
$cart_item_data['custom_data']['quantity'] = $_REQUEST['quantity_prod'];
$data['quantity'] = $_REQUEST['quantity_prod'];
}
// below statement make sure every add to cart action as unique line item
$cart_item_data['custom_data']['unique_key'] = md5( microtime().rand() );
WC()->session->set( 'price_calculation', $data );
return $cart_item_data;
}
Step 3: you need to override the item price with your custom calculation. It will work with your every scenario of your single product sessions.
add_action( 'woocommerce_before_calculate_totals', 'add_custom_item_price', 10 );
function add_custom_item_price( $cart_object ) {
foreach ( $cart_object->get_cart() as $item_values ) {
## Get cart item data
$item_id = $item_values['data']->id; // Product ID
$original_price = $item_values['data']->price; // Product original price
## Get your custom fields values
$price1 = $item_values['custom_data']['price1'];
$quantity = $item_values['custom_data']['quantity'];
// CALCULATION FOR EACH ITEM:
## Make HERE your own calculation
$new_price = $price1 ;
## Set the new item price in cart
$item_values['data']->set_price($new_price);
}
}
Everything will be done inside the functions.php
Reference Site