I am making a custom add-on for my products on my WooCommerce webshop. Everything works as it should, but I only need one thing. When customers check the checkbox on the product page, $30 must be added to the original price of the selected variation.
add_filter( 'woocommerce_add_cart_item_data', 'add_cart_item_data', 10, 3 );
function add_cart_item_data( $cart_item_data, $product_id, $variation_id ) {
$product = wc_get_product($product_id);
$price = $product->get_price();
if ($product->is_type( 'variable' )) {
$var_price = $product->get_price_html();
// extra pack checkbox
if( ! empty( $_POST['addon-card'] ) ) {
$cart_item_data['new_price'] = $var_price + 30;
}
} else {
// extra pack checkbox
if( ! empty( $_POST['addon-card'] ) ) {
$cart_item_data['new_price'] = $price + 30;
}
}
return $cart_item_data;
}
This part: if( ! empty( $_POST['addon-card'] ) ) check if the checkbox is checked.
My problem is here:
$var_price = $product->get_price_html();
// extra pack checkbox
if( ! empty( $_POST['addon-card'] ) ) {
$cart_item_data['new_price'] = $var_price + 30;
}
The value of $var_price is just 0.
So I try to figure out how I can get the price of the chosen variation.
I have tried with get_variation_prices() and get_variation_price() but without any luck...
UPDATE
I have tried to implement the code from this thread. With that code I can get the price of the chosen variation, but I can no longer add the $30.
Can you please try below WooCommerce hook to change price dynamically?
add_filter('woocommerce_variation_prices_price', 'custom_variation_price_change', 10, 3 );
add_filter('woocommerce_variation_prices_regular_price', 'custom_variation_price_change', 10, 3 );
function custom_variation_price_change( $price, $variation, $product ) {
// add some conditional code as per your requirement
$price = $price+30;
}
Related
I've tried several variations of this so far. I am trying to set the max quantity of any single product, or variable product variation at a maximum of 6 for purchase. I'm using Add to cart maximun quantity per product with validation in WooCommerce answer code
the problem with this is:
it doesn't check on the product page, instead, it allows it to be added to the cart at any quantity without an error message, then when you navigate to the cart it performs the check, automatically updates the cart (again no error message displaying why the cart updates to 6).
In case it's relevant I have also successfully added a function that allows no more than 6 to be added to the cart at a time. (this doesn't help my issue because someone can just keep adding on the product page itself.
Source: Adjust the quantity input values
add_filter( 'woocommerce_quantity_input_args', 'jk_woocommerce_quantity_input_args', 10, 2 ); // Simple products
function jk_woocommerce_quantity_input_args( $args, $product ) {
if ( is_singular( 'product' ) ) {
$args['input_value'] = 1; // Starting value (we only want to affect product pages, not cart)
}
$args['max_value'] = 6; // Maximum value
$args['min_value'] = 1; // Minimum value
$args['step'] = 1; // Quantity steps
return $args;
}
add_filter( 'woocommerce_available_variation', 'jk_woocommerce_available_variation' ); // Variations
function jk_woocommerce_available_variation( $args ) {
$args['max_qty'] = 6; // Maximum value (variations)
$args['min_qty'] = 1; // Minimum value (variations)
return $args;
}
You can WC woocommerce_add_to_cart_validation filter hook where you can set max quantity and then check max quantity against product cart quantity. check below code. code will go to the active theme functions.php file.
/*
* Validating the quantity on add to cart action with the quantity of the same product available in the cart.
*/
function show_error_on_max_quantity_reached( $passed, $product_id, $quantity, $variation_id = '', $variations = '' ) {
$product_max = 6;
$already_in_cart = wc_qty_get_cart_qty( $product_id );
$product = wc_get_product( $product_id );
$product_title = $product->get_title();
if ( !empty( $already_in_cart ) ) {
if ( ( $already_in_cart + $quantity ) > $product_max ) {
$passed = false;
wc_add_notice(
sprintf( __( 'Sorry, You can add a maximum of %1$s %2$s\'s to %3$s. You already have %4$s.', 'woocommerce-max-quantity' ),
$product_max,
$product_title,
'' . __( 'Your cart', 'woocommerce-max-quantity' ) . '',
$already_in_cart
),
'error' );
}
}
return $passed;
}
add_filter( 'woocommerce_add_to_cart_validation', 'show_error_on_max_quantity_reached', 1, 5 );
/*
* Get the total quantity of the product available in the cart.
*/
function wc_qty_get_cart_qty( $product_id , $cart_item_key = '' ) {
global $woocommerce;
$running_qty = 0; // iniializing quantity to 0
// search the cart for the product in and calculate quantity.
foreach($woocommerce->cart->get_cart() as $other_cart_item_keys => $values ) {
if ( $product_id == $values['product_id'] ) {
if ( $cart_item_key == $other_cart_item_keys ) {
continue;
}
$running_qty += (int) $values['quantity'];
}
}
return $running_qty;
}
Tested and works.
I'm trying to overwrite the price for a product in the WooCommerce cart.
The problem is that I'm using Divi which includes an ajax cart update. So when I reload the checkout page I can see my overwritten changes for 1-2 seconds (during the ajax loading) and after this the cart details get overwritten again by the default values. I've tried everythink, different hooks, delays, priority changes but nothing works.
This is my initial code:
add_filter( 'woocommerce_calculate_totals', 'custom_cart_items_prices', 1000, 1 )
function custom_cart_items_prices( $cart_object ) {
$title = $_GET['form-title'];
$money = $_GET['money'];
if ($title && $money) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Iterating through cart items
foreach ( $cart_object->get_cart() as $cart_item ) {
// Get an instance of the WC_Product object
$wc_product = $cart_item['data'];
// Get the product name (WooCommerce versions 2.5.x to 3+)
$original_name = method_exists( $wc_product, 'get_name' ) ? $wc_product->get_name() : $wc_product->post->post_title;
// SET THE NEW NAME
$new_name = $title;
// Set the new name (WooCommerce versions 2.5.x to 3+)
if( method_exists( $wc_product, 'set_name' ) )
$wc_product->set_name( $new_name );
else
$wc_product->post->post_title = $new_name;
}
// Updated cart item price
$cart_item['data']->set_price( $money );
}}
Picture during the loading (Everything looks great):
When the loading is completed:
Update - I've also tried a different approach as I am using a custom form made with CRED Toolset and Toolset Woocommerce plugins where customer create a product with a custom title and price, adding to cart a default existing product (and redirected to checkout page). I am trying to replace the cart item title and price by the submitted form data.
Here is my code:
// Change the product ID
add_filter('cred_commerce_add_product_to_cart', function( $product_id, $form_id, $post_id ) {
error_log($form_id);
if( $form_id == 55 ) {
if (!session_id()) {
session_start();
}
$_SESSION['target_post_id'] = $post_id;
if(isset($_POST['product-id'])){
$product_id = $_POST['product-id'];
$_SESSION['target_post_id'] = $post_id;
}
}
return $product_id;
}, 20, 3);
// change the price in cart
add_action('woocommerce_before_calculate_totals', function(){
session_start();
if($form_id != 55 && !isset($_SESSION['target_post_id']))return;
global $woocommerce;
$post_id = $_SESSION['target_post_id'];
$price = 0;
foreach ( $woocommerce->cart->get_cart() as $key => $cart_item ) {
$product_id = $cart_item['data']->get_id();
$adult_price = get_post_meta($product_id, 'wpcf-prezzo-1', true);
$adult_num = get_post_meta($post_id, 'wpcf-adult-number', true);
$child_price = get_post_meta($product_id, 'wpcf-prezzo-2', true);
$child_num = get_post_meta($post_id, 'wpcf-children-number', true);
$price = $adult_price * $adult_num + $child_price * $child_num;
$cart_item['data']->set_price($price);
}
}, 999);
But it doesn't work either.
How can I get the submitted form data (custom title and price) and to overwrite the cart item title and price in Woocommerce?
Try the following instead as you are using the toolset plugin with a custom form, where you will use WC_Sessions to store the product ID and change the price:
add_filter( 'cred_commerce_add_product_to_cart', 'cred_commerce_add_product_to_cart', 20, 3 );
function cred_commerce_add_product_to_cart( $product_id, $form_id, $post_id ) {
if( $form_id == 55 && $post_id > 0 ) {
WC()->session->set( 'cp_id', $post_id );
}
return $product_id;
}
add_filter( 'woocommerce_add_cart_item_data', 'filter_add_cart_item_data', 30, 4 );
function filter_add_cart_item_data( $cart_item_data, $product_id, $variation_id ){
if ( WC()->session->get('cp_id') ) {
$cp_id = WC()->session->get('cp_id');
$product = wc_get_product($cp_id);
$cart_item_data['cp_price'] = $product->get_regular_price();
$cart_item_data['cp_title'] = $product->get_title();
}
return $cart_item_data;
}
add_action( 'woocommerce_before_calculate_totals', 'custom_cart_items_price', 30, 1 );
function custom_cart_items_price( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// Iterating through cart items
foreach ( $cart->get_cart() as $cart_item ) {
if( isset($cat_item['cp_price']) && isset($cat_item['cp_title']) ){
$cart_item['data']->set_price( $cat_item['cp_price'] );
$cart_item['data']->set_name( $cat_item['cp_title'] );
}
}
}
Code goes in function.php file of your active child theme (or active theme). It should works.
Some related answers:
Set cart item price from a hidden input field custom price in Woocommerce 3
Custom cart item price based on user input in Woocommerce
Conditionally alter specific product price in Woocommerce
Change cart item prices in Woocommerce 3
Deactivate all of your plugins and voila!
You will suprisingly understand that its a cause of one.
Enabling them one by one back, will let you know which one is conflicting.
And.. Please consider using WordPress stack exchange for WordPress-specific questions.
1 woocommerce_add_cart_item_data
add_filter( 'woocommerce_add_cart_item_data', function($cart_item_data, $product_id, $variation_id ){
if ( empty( $_GET['form-title'] ) || empty( $_GET['money'] ) ) {
return;
}
$title = $_GET['form-title'];
$money = $_GET['money'];
$cart_item_data['form-title'] = $title ;
$cart_item_data['money'] = $money ;
return $cart_item_data;
} ,100,4);
2 woocommerce_before_calculate_totals
add_action( 'woocommerce_before_calculate_totals', 'update_custom_price', 10, 1 );
function update_custom_price( $cart_object ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
return;
}
foreach ( $cart_object->cart_contents as $cart_item_key => $cart_item ) {
if(isset($cart_item["money"]) ){
$money = $cart_item["money"] ;
$cart_item['data']->set_price( $money);
}
if(isset($cart_item["form-title"]) ){
$title = $cart_item["form-title"] ;
}
$wc_product = $cart_item['data'];
// Get the product name (WooCommerce versions 2.5.x to 3+)
$original_name = method_exists( $wc_product, 'get_name' ) ? $wc_product->get_name() : $wc_product->post->post_title;
// SET THE NEW NAME
$new_name = $title;
// Set the new name (WooCommerce versions 2.5.x to 3+)
if( method_exists( $wc_product, 'set_name' ) )
$wc_product->set_name( $new_name );
else
$wc_product->post->post_title = $new_name;
}
}
return $cart_object ;
}
Hope this will help.
There is a field on the main page with a numerical parameter:
length
and button - add to cart like:
add to cart
I would like to calculate the price of the goods from this parameter.
I understood how to change the price when adding to the basket but I can not understand how to transfer the numerical parameter of the field to the function in functions.php
The biggest problem is that the field is not on the single product page.
I think that you can pass a parameter through a link by type:
add to cart
But I could not get it in function yet.
add_action( 'woocommerce_before_shipping_calculator', 'add_custom_price' );
global $woocommerce;
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
if($cart_item['data']->id == ####){
$original_price = $cart_item['data']->price;
$length = $_GET('length');
$new_price = $original_price + $length;
$cart_item['data']->set_price($new_price);
}
}
}
Using the following 2 hooked functions will allow you to set a new cart item price calculated on a Get "length" parameter this way:
// Set custom text and calculated price as custom cart data in the cart item
add_filter( 'woocommerce_add_cart_item_data', 'save_new_price_in_cart_object', 30, 3 );
function save_new_price_in_cart_object( $cart_item_data, $product_id, $variation_id ) {
if( ! isset( $_GET['length'] ) )
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 lenght
$length = esc_attr( $_GET['length'] );
// Set the new calculated price as custom cart data for the cart item
$cart_item_data['custom_data']['price'] = $product_price + $length;
return $cart_item_data;
}
// Set the new calculated price of the cart item
add_action( 'woocommerce_before_calculate_totals', 'set_new_cart_item_price', 90, 1 );
function set_new_cart_item_price( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
foreach ( $cart->get_cart() as $cart_item ) {
if( isset( $cart_item['custom_data']['price'] ) ) {
// Get the new calculated price
$new_price = (float) $cart_item['custom_data']['price'];
// Set the new calculated price
$cart_item['data']->set_price( $new_price );
}
}
}
Code goes in function.php file of your active child theme (or active theme).
Tested and works
I have set up a hidden input item using woocommerce_before_add_to_cart_button hook
function add_gift_wrap_field() {
?>`<input type="hidden" id="price_val" name="added_price" value="100.34">`<?php
}
add_action( 'woocommerce_before_add_to_cart_button', 'add_gift_wrap_field' );
Saving fields against the product:
function save_gift_wrap_fee( $cart_item_data, $product_id ) {
if( isset( $_POST['added_price'] ) ) {
$cart_item_data = array();
$cart_item_data[ "gift_wrap_fee" ] = "YES";
$cart_item_data[ "gift_wrap_price" ] = 100;
}
return $cart_item_data;
}
add_filter( 'woocommerce_add_cart_item_data', 'save_gift_wrap_fee', 99, 2 );
Now I can echo out the $_POST['added_price'] inside this woocommerce_before_calculate_totals hook.
The code I written is shown below:
function calculate_gift_wrap_fee( $cart_object ) {
if( !WC()->session->__isset( "reload_checkout" )) {
/* Gift wrap price */
$additionalPrice = number_format($_POST['added_price'], 2);
$additionalPrice = floatval($additionalPrice);
//echo $additionalPrice; exit(); shows the value
foreach ( $cart_object->cart_contents as $key => $value ) {
if( isset( $value["gift_wrap_fee"] ) ) {
/* Woocommerce 3.0 + */
$orgPrice = floatval( $value['data']->get_price() );
$value['data']->set_price( $orgPrice + $additionalPrice ); //not adding the $additionalPrice here.
}
}
}
}
add_action( 'woocommerce_before_calculate_totals', 'calculate_gift_wrap_fee', 99 );
What am I doing wrong here?
Here is the complete clean, tested and working solution based on your code question.
Here I have included your custom field key/value in the cart object for the related cart item, instead of getting the Post value in your calculate_gift_wrap_fee() function.
This way it's not possible to loose the custom field value and the new price calculation is reliable.
I have commented 'gift_wrap_fee' and 'gift_wrap_price' as they are not really needed now (but you can uncomment them if you like).
Here is this code:
// The hidden product custom field
add_action( 'woocommerce_before_add_to_cart_button', 'add_gift_wrap_field' );
function add_gift_wrap_field() {
?>
<input type="hidden" id="price_val" name="added_price" value="100.34">
<?php
}
// Adding the custom field to as custom data for this cart item in the cart object
add_filter( 'woocommerce_add_cart_item_data', 'save_custom_fields_data_to_cart', 10, 2 );
function save_custom_fields_data_to_cart( $cart_item_data, $product_id ) {
$bool = false;
$data = array();
if( ! empty( $_REQUEST['added_price'] ) ) {
$cart_item_data['custom_data']['added_price'] = $_REQUEST['added_price'];
// Below this 2 values are not really needed (I think)
// (You can uncomment them if needed)
## $cart_item_data['custom_data']['gift_wrap_fee'] = 'YES';
## $cart_item_data['custom_data']['gift_wrap_price'] = 100;
// 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( 'custom_data', $data );
}
return $cart_item_data;
}
// Changing the cart item price based on custom field calculation
add_action( 'woocommerce_before_calculate_totals', 'calculate_gift_wrap_fee', 10, 1 );
function calculate_gift_wrap_fee( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// Iterating though cart items
foreach ( $cart->get_cart() as $cart_item ) {
// Continue if we get the custom data for the current cart item
if( ! empty( $cart_item['custom_data'] ) ){
// Get the custom field "added price" value
$added_price = number_format( $cart_item['custom_data']['added_price'], 2 );
// The WC_Product object
$product = $cart_item['data'];
// Get the price (WooCommerce versions 2.5.x to 3+)
$product_price = method_exists( $product, 'get_price' ) ? floatval(product->get_price()) : floatval($product->price);
// New price calculation
$new_price = $product_price + $added_price;
// Set the calculeted price (WooCommerce versions 2.5.x to 3+)
method_exists( $product, 'set_price' ) ? $product->set_price( $new_price ) : $product->price = $new_price;
}
}
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
This code is tested and works on WooCommerce versions from 2.5.x to 3+.
I have set up a hidden input item using woocommerce_before_add_to_cart_button hook
function add_gift_wrap_field() {
?>`<input type="hidden" id="price_val" name="added_price" value="100.34">`<?php
}
add_action( 'woocommerce_before_add_to_cart_button', 'add_gift_wrap_field' );
Saving fields against the product:
function save_gift_wrap_fee( $cart_item_data, $product_id ) {
if( isset( $_POST['added_price'] ) ) {
$cart_item_data = array();
$cart_item_data[ "gift_wrap_fee" ] = "YES";
$cart_item_data[ "gift_wrap_price" ] = 100;
}
return $cart_item_data;
}
add_filter( 'woocommerce_add_cart_item_data', 'save_gift_wrap_fee', 99, 2 );
Now I can echo out the $_POST['added_price'] inside this woocommerce_before_calculate_totals hook.
The code I written is shown below:
function calculate_gift_wrap_fee( $cart_object ) {
if( !WC()->session->__isset( "reload_checkout" )) {
/* Gift wrap price */
$additionalPrice = number_format($_POST['added_price'], 2);
$additionalPrice = floatval($additionalPrice);
//echo $additionalPrice; exit(); shows the value
foreach ( $cart_object->cart_contents as $key => $value ) {
if( isset( $value["gift_wrap_fee"] ) ) {
/* Woocommerce 3.0 + */
$orgPrice = floatval( $value['data']->get_price() );
$value['data']->set_price( $orgPrice + $additionalPrice ); //not adding the $additionalPrice here.
}
}
}
}
add_action( 'woocommerce_before_calculate_totals', 'calculate_gift_wrap_fee', 99 );
What am I doing wrong here?
Here is the complete clean, tested and working solution based on your code question.
Here I have included your custom field key/value in the cart object for the related cart item, instead of getting the Post value in your calculate_gift_wrap_fee() function.
This way it's not possible to loose the custom field value and the new price calculation is reliable.
I have commented 'gift_wrap_fee' and 'gift_wrap_price' as they are not really needed now (but you can uncomment them if you like).
Here is this code:
// The hidden product custom field
add_action( 'woocommerce_before_add_to_cart_button', 'add_gift_wrap_field' );
function add_gift_wrap_field() {
?>
<input type="hidden" id="price_val" name="added_price" value="100.34">
<?php
}
// Adding the custom field to as custom data for this cart item in the cart object
add_filter( 'woocommerce_add_cart_item_data', 'save_custom_fields_data_to_cart', 10, 2 );
function save_custom_fields_data_to_cart( $cart_item_data, $product_id ) {
$bool = false;
$data = array();
if( ! empty( $_REQUEST['added_price'] ) ) {
$cart_item_data['custom_data']['added_price'] = $_REQUEST['added_price'];
// Below this 2 values are not really needed (I think)
// (You can uncomment them if needed)
## $cart_item_data['custom_data']['gift_wrap_fee'] = 'YES';
## $cart_item_data['custom_data']['gift_wrap_price'] = 100;
// 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( 'custom_data', $data );
}
return $cart_item_data;
}
// Changing the cart item price based on custom field calculation
add_action( 'woocommerce_before_calculate_totals', 'calculate_gift_wrap_fee', 10, 1 );
function calculate_gift_wrap_fee( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// Iterating though cart items
foreach ( $cart->get_cart() as $cart_item ) {
// Continue if we get the custom data for the current cart item
if( ! empty( $cart_item['custom_data'] ) ){
// Get the custom field "added price" value
$added_price = number_format( $cart_item['custom_data']['added_price'], 2 );
// The WC_Product object
$product = $cart_item['data'];
// Get the price (WooCommerce versions 2.5.x to 3+)
$product_price = method_exists( $product, 'get_price' ) ? floatval(product->get_price()) : floatval($product->price);
// New price calculation
$new_price = $product_price + $added_price;
// Set the calculeted price (WooCommerce versions 2.5.x to 3+)
method_exists( $product, 'set_price' ) ? $product->set_price( $new_price ) : $product->price = $new_price;
}
}
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
This code is tested and works on WooCommerce versions from 2.5.x to 3+.