Custom cart item price based on user input in Woocommerce - php

in our Woocommerce store we have some minimum price for any products . And in every product inner page there is two filed where customer can type width , height of the product . And then they can add this product to cart, then price is changed based on given width and height.
For example if the minimum price for a product is 50 . And customer add width =2, height=3 , then the price for this product is going to 50*2*3=300
So to arrange this we add this code to function.php
add_filter( 'woocommerce_add_cart_item', 'add_custom_cart_item_data', 10, 2 );
function add_custom_cart_item_data( $cart_item_data, $cart_item_key ) {
$result=$_POST['width']*$_POST['height']*$cart_item_data['data']->price;
$cart_item_data['new-price'] =$result;
$cart_item_data['data']->set_price($result);
return $cart_item_data;
}
So this is working correctly .
But the problem is once it is coming to checkout page then the product price is showing as 50 , but it is 300 actually.
so to overcome this i use the following code
add_filter( 'woocommerce_cart_item_subtotal', 'update_with_custom_details', 10, 3 );
function update_with_custom_details( $subtotal, $cart_item, $cart_item_key ) {
$subtotal =" £".$cart_item['line_total'];
return $subtotal;
}
now it is showing £300, but i know this code is wrong.
The code is wrong because when customer apply a 50% coupon code for this product then the discount is coming as 25 , Because it calculating based on 50*.5=25; But actually product new price is 300, so the discount should be 300*5=150;
So how i can update the product price in cart page, checkout page ,mini cart etc ?
Please help .
Please see this also
Woocommerce product custom price is not accepted by wocommerce coupon

Update 2: The correct way to do it need to be done in two steps:
We calculate the price on add to cart event hook and save it as custom cart item data.
We set that calculated price in woocommerce_before_calculate_totals hook
The code:
// Save custom field value in cart item as custom data
add_filter( 'woocommerce_add_cart_item_data', 'calculate_custom_cart_item_prices', 30, 3 );
function calculate_custom_cart_item_prices( $cart_item_data, $product_id, $variation_id ) {
if ( isset($_POST['width']) && isset($_POST['height']) ) {
// Get the correct Id to be used (compatible with product variations)
$the_id = $variation_id > 0 ? $variation_id : $product_id;
$product = wc_get_product( $the_id ); // Get the WC_Product object
$product_price = (float) $product->get_price(); // Get the product price
// Get the posted data
$width = (float) sanitize_text_field( $_POST['width'] );
$height = (float) sanitize_text_field( $_POST['height'] );
$new_price = $width * $height * $product_price; // Calculated price
$cart_item_data['calculated-price'] = $new_price; // Save this price as custom data
}
return $cart_item_data;
}
// Set custom calculated price in cart item price
add_action( 'woocommerce_before_calculate_totals', 'set_calculated_cart_item_price', 20, 1 );
function set_calculated_cart_item_price( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// Loop through cart items
foreach ( $cart->get_cart() as $cart_item ){
if( ! empty( $cart_item['calculated-price'] ) ){
// Set the calculated item price (if there is one)
$cart_item['data']->set_price( $cart_item['calculated-price'] );
}
}
}
Code goes in function.php file of your active child theme (or theme). Tested and works.
For testing purpose, I have used the following code that output 2 custom fields on single product pages:
// The hidden product custom field
add_action( 'woocommerce_before_add_to_cart_button', 'add_gift_wrap_field' );
function add_gift_wrap_field() {
global $product;
// The fake calculated price
?>
<div>
<label class="product-custom-text-label" for="servicetime"><?php _e( 'Custom text:', 'woocommerce'); ?><br>
<input type="text" id="user-width" name="width" value=""><br>
<input type="text" id="user-height" name="height" value="">
</label>
</div><br>
<?php
}

Related

Update woocommerce price of a product based on php

I have a custom add to cart button in php for a single product:
Final total<br>
$<?php echo $row['purchase-price'] ?>.00<br><br>
<button onclick="window.location.href='https://yourdomain.com/checkout/?add-to-cart=362166';">Add to cart</button>
After clicking the button, it returned a "Sorry, this product cannot be purchased." error. I havent set the product price since the amount in <?php echo $row['purchase-price'] ?> is always changing. How to pass the amount set in php and pass it to product's final price?
First you will restrict your code to single product and archives pages only:
add_filter( 'woocommerce_product_get_price', 'double_price', 10, 2 );
function double_price( $price, $product ){
if( is_shop() || is_product_category() || is_product_tag() || is_product() ) {
global $wpdb;
//your query to get price from custom db
//FOR GET PRODUCT ID $product->get_id();
$price = $row['purchase-price'];
}
return $price;
}
Then for cart and checkout pages, you will change the cart item price this way:
add_filter( 'woocommerce_add_cart_item', 'set_custom_cart_item_prices', 20, 2 );
function set_custom_cart_item_prices( $cart_data, $cart_item_key ) {
global $wpdb;
//your query to get price from custom db
$new_price = $row['purchase-price'];
//FOR GET PRODUCT ID $cart_item['data']->get_id();
// Set and register the new calculated price
$cart_data['data']->set_price( $new_price );
$cart_data['new_price'] = $new_price;
return $cart_data;
}
add_filter( 'woocommerce_get_cart_item_from_session', 'set_custom_cart_item_prices_from_session', 20, 3 );
function set_custom_cart_item_prices_from_session( $session_data, $values, $key ) {
if ( ! isset( $session_data['new_price'] ) || empty ( $session_data['new_price'] ) )
return $session_data;
// Get the new calculated price and update cart session item price
$session_data['data']->set_price( $session_data['new_price'] );
return $session_data;
}
And in the last hit your custom url
<button onclick="window.location.href='https://yourdomain.com/?add-to-cart=362166&quantity=1';">Add to cart</button>

Target specific product IDs on WooCommerce cart displayed quantity

I am using this code to make the product show boxes in cart but I just want it to show it on certain products. How can I put the product id?
function cw_change_product_quantity_display( $quantity ) {
$quantity .= ' Caja (s)';
return $quantity;
}
add_filter( 'woocommerce_get_quantity_html', 'cw_change_product_quantity_display' );
add_filter( 'woocommerce_cart_item_quantity', 'cw_change_product_quantity_display' );
The hook woocommerce_get_quantity_html is not defined in WooCommerce core, so maybe it's a custom hook added by a third party plugin, your theme or by yourself…
Now for the hook woocommerce_cart_item_quantity, there are 2 additional optional arguments missing from your code that will allow you to target a product ID like:
add_filter( 'woocommerce_cart_item_quantity', 'change_cart_item_displayed_quantity', 10, 3 );
function change_cart_item_displayed_quantity( $product_quantity, $cart_item_key, $cart_item ) {
// Here define your product ID(s) in the array
$product_ids = array( 37, 53 );
if( array_intersect( [ $cart_item['product_id'], $cart_item['variation_id'] ], $product_ids ) ) {
$product_quantity .= __(' Caja (s)');
}
return $product_quantity;
}
It should work for some defined product IDs only.
But as $product quantity is an input number field, your custom text will be display after this quantity field, which is strange.

Discount based on WooCommerce product custom input fields

I'm trying to give the user a discount based on a quantity field in the single product page.
Basically, the website sells tickets and I have a different price for adults and for children. So I created input fields in the single product page so the user would type how many adults and how many children he is buying for.
In the product admin I have a ACF (advanced custom field) for "children discount", so in the cart I want to give this discount based on the amount of children. For example, let's say that for this product the user is buying 5 tickets, 3 for adults and 2 for children, I want to calculate a discount for these 2 children.
What I've tried so far:
add_action( 'woocommerce_before_add_to_cart_button', 'custom_product_price_field', 5 );
function custom_product_price_field(){
echo '<div class="custom-text text">
<p>Quantity of adults:</p>
<input type="text" name="qtty_adults" value="" title="Quantity Adults" class="qtty-field">
</div>
<div class="custom-text text">
<p>Quantity of children:</p>
<input type="text" name="qtty_kids" value="" title="Quantity Kids" class="qtty-field">
</div>';
}
add_action('woocommerce_cart_calculate_fees' , 'add_user_discounts');
function add_user_discounts( WC_Cart $cart ){
global $product;
$qtty_kids = (float) sanitize_text_field( $_POST['qtty_kids'] );
$discount_per_kid = (float) get_field('children_discount', $product->id);
$discount = $qtty_kids * $discount_per_kid;
$cart->add_fee( 'Discount for children', -$discount);
}
Doing this the discount is always $0
Can anyone give me some help on how to make this happen?
Your code is a bit outdated, with some mistakes and there is a lot of missing things to get what you expect…
Try the following instead (updated):
add_action( 'woocommerce_before_add_to_cart_button', 'custom_product_price_field', 5 );
function custom_product_price_field(){
echo '<div class="custom-text text">
<p>'.__("Quantity of adults:").'</p>
<input type="text" name="qtty_adults" value="" title="'.__("Quantity Adults").'" class="qtty-field">
</div>
<div class="custom-text text">
<p>'.__("Quantity of children:").'</p>
<input type="text" name="qtty_kids" value="" title="'.__("Quantity Kids").'" class="qtty-field">
</div>';
}
// Add selected add-on option as custom cart item data
add_filter( 'woocommerce_add_cart_item_data', 'filter_add_cart_item_data_callback', 10, 3 );
function filter_add_cart_item_data_callback( $cart_item_data, $product_id, $variation_id ) {
if ( isset( $_POST['qtty_kids'] ) && $children_discount = get_field( 'children_discount', $product_id ) ) {
$cart_item_data['children_discount'] = (float) $children_discount - (float) sanitize_text_field( $_POST['qtty_kids'] );
$cart_item_data['unique_key'] = md5( microtime().rand() ); // Make each item unique
}
return $cart_item_data;
}
// Set a discount based a product custom field(s)
add_action('woocommerce_cart_calculate_fees' , 'add_children_discount', 10, 1 );
function add_children_discount( $cart ){
if ( is_admin() && ! defined('DOING_AJAX') )
return;
if ( did_action('woocommerce_cart_calculate_fees') >= 2 )
return;
$discount = 0; // Initialising
// Loop through cart items
foreach ( $cart->get_cart() as $cart_item ) {
if( isset( $cart_item['children_discount'] ) ) {
$discount += $cart_item['children_discount'];
}
}
if ( $discount > 0 )
$cart->add_fee( __("Discount for children", "woocommerce"), -$discount );
}
Tested and works.
Related:
Cart item discount based on quantity in Woocommerce 3

Cart item discount based on quantity in Woocommerce 3

My WP site sells customized t-shirts. The customization plugin makes each customized shirt a line item in the woocommerce cart. If there are 2 shirts ordered of one design (quantity of 2 on that line item) I want to discount. But if there is just 1 item per line I dont want to discount.
I found this solution
Adding a discount by cart items conditionally based on the item quantity
But this seems to change the product price in the db, so after the discount kicks in for say 2 blue shirts because there were 2 ordered on 1 line, if I add a 3rd shirt on a separate line it also gets the discount, which I dont want.
Since woocommerce version 3+ the linked answer code doesn't work. It needs something different and can even be done in a better way.
The code will apply a cart item discount based on the cart item quantity. In this code example, it will apply a discount of 5% on the cart item, when the quatity is equal or more than 2 (two).
The cart item unit price displayed is always the real product price. The discount will be effective and displayed on the cart item subtotal.
Additionally the product name will be appended with a discount mention.
The code:
add_filter('woocommerce_add_cart_item_data', 'add_items_default_price_as_custom_data', 20, 3 );
function add_items_default_price_as_custom_data( $cart_item_data, $product_id, $variation_id ){
$product_id = $variation_id > 0 ? $variation_id : $product_id;
## ----- YOUR SETTING ----- ##
$discount_percentage = 5; // Discount (5%)
// The WC_Product Object
$product = wc_get_product($product_id);
// Only for non on sale products
if( ! $product->is_on_sale() ){
$price = (float) $product->get_price();
// Set the Product default base price as custom cart item data
$cart_item_data['base_price'] = $price;
// Set the Product discounted price as custom cart item data
$cart_item_data['new_price'] = $price * (100 - $discount_percentage) / 100;
// Set the percentage as custom cart item data
$cart_item_data['percentage'] = $discount_percentage;
}
return $cart_item_data;
}
// Display the product original price
add_filter('woocommerce_cart_item_price', 'display_cart_items_default_price', 20, 3 );
function display_cart_items_default_price( $product_price, $cart_item, $cart_item_key ){
if( isset($cart_item['base_price']) ) {
$product = $cart_item['data'];
$product_price = wc_price( wc_get_price_to_display( $product, array( 'price' => $cart_item['base_price'] ) ) );
}
return $product_price;
}
// Display the product name with the discount percentage
add_filter( 'woocommerce_cart_item_name', 'append_percetage_to_item_name', 20, 3 );
function append_percetage_to_item_name( $product_name, $cart_item, $cart_item_key ){
if( isset($cart_item['percentage']) && isset($cart_item['base_price']) ) {
if( $cart_item['data']->get_price() != $cart_item['base_price'] )
$product_name .= ' <em>(' . $cart_item['percentage'] . '% discounted)</em>';
}
return $product_name;
}
add_action( 'woocommerce_before_calculate_totals', 'custom_discounted_cart_item_price', 20, 1 );
function custom_discounted_cart_item_price( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
## ----- YOUR SETTING ----- ##
$targeted_qty = 2; // Targeted quantity
// Loop through cart items
foreach ( $cart->get_cart() as $cart_item ) {
// For item quantity of 2 or more
if( $cart_item['quantity'] >= $targeted_qty && isset($cart_item['new_price']) ){
// Set cart item discounted price
$cart_item['data']->set_price($cart_item['new_price']);
}
}
}
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
To display the discounted product price instead of the original product price, just remove woocommerce_cart_item_price() function (and hook)…
Newest similar: Cart item quantity progressive percentage discount in Woocommerce 3

Checkout price issue using woocommerce_product_get_price hook

I need to double the price for every product in Woocommerce frontend. For this I used the following code:
add_filter( 'woocommerce_product_get_price', 'double_price', 10, 2 );
function double_price( $price, $product ){
return $price*2;
}
But there is an error using this code. checkout page price is not correct.
for example the product orginal price is 10. We double the price by this code . so the product price is 20 now. When i added this product to the cart then cart and checkout page price is 40. That means this multiplication is take place in two times.
Please help to solve this.
Updated To double the price:
1) First you will restrict your code to single product and archives pages only:
add_filter( 'woocommerce_product_get_price', 'double_price', 10, 2 );
function double_price( $price, $product ){
if( is_shop() || is_product_category() || is_product_tag() || is_product() )
return $price*2;
return $price;
}
2) Then for cart and checkout pages, you will change the cart item price this way:
add_filter( 'woocommerce_add_cart_item', 'set_custom_cart_item_prices', 20, 2 );
function set_custom_cart_item_prices( $cart_data, $cart_item_key ) {
// Price calculation
$new_price = $cart_data['data']->get_price() * 2;
// Set and register the new calculated price
$cart_data['data']->set_price( $new_price );
$cart_data['new_price'] = $new_price;
return $cart_data;
}
add_filter( 'woocommerce_get_cart_item_from_session', 'set_custom_cart_item_prices_from_session', 20, 3 );
function set_custom_cart_item_prices_from_session( $session_data, $values, $key ) {
if ( ! isset( $session_data['new_price'] ) || empty ( $session_data['new_price'] ) )
return $session_data;
// Get the new calculated price and update cart session item price
$session_data['data']->set_price( $session_data['new_price'] );
return $session_data;
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
Tested and working. It will change all prices as you expect in cart, checkout and order pages…

Categories