WooCommerce Cart - Dynamic Price variable pass into custom price hook - php

I am getting the dynamic custom price in a variable that I want to pass to the hooked function in woocommerce_before_calculate_totals hook in cart. But it isn't working.
This is my code:
$add=200; //I want to pass this variable in add_action hook
add_action( 'woocommerce_before_calculate_totals', 'add_custom_total_price');
function add_custom_total_price($cart_object) {
global $woocommerce;
$custom_price =$add; // This is my custom price
foreach ( $cart_object->cart_contents as $key => $value ) {
$value['data']->price = $custom_price;
}
}
How can I achieve this?
Thanks

To make it work you just need to define $custom_price variables as global in your function, this way:
$custom_price = 200;
add_action( 'woocommerce_before_calculate_totals', 'add_custom_item_price', 10, 1 );
function add_custom_item_price( $cart_object ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
global $custom_price;
foreach ( $cart_object->get_cart() as $item_values ) {
$item_values['data']->price = $custom_price;
}
}
This code is tested and working (for woocommerce versions 2.5+ and 2.6+).
Naturally this code goes on function.php file of your active child theme or theme.

To add Price in your woocommerce cart before calculate total -
add_action( 'woocommerce_before_calculate_totals', 'add_custom_total_price');
function add_custom_total_price($cart_object) {
global $woocommerce,$add,$custom_price;
$add=200;//Dynamic Price variable
$custom_price =$add;//Dynamic Price variable pass to custom price
foreach ( $cart_object->cart_contents as $key => $value ) {
$value['data']->price = $custom_price;
}
}

Related

Replace quantity field with a form if product is out of stock in Woocommerce

In woocommerce, using contact Form 7 plugin, I'm trying to replace the product quantity field, in the product summary, with a form, when a product is out of stock.
It works fine on variable products but on simple products it still shows the form and the quantity box.
It feels like I'm overlooking something very basic.
I've replaced the different echo with "simple" and "variable" to find out which form is shown, but on simple products it still shows the 'variable' form.
Here is my code:
add_action( 'woocommerce_single_product_summary', 'add_form' );
function add_form() {
global $product;
if( $product->is_type( 'simple' ) ){
// a simple product
if(!$product->is_in_stock( )) {
echo do_shortcode('[contact-form-7 id="304" title="Contact stock"]');
//echo "simple";
}
} elseif( $product->is_type( 'variable' ) ){
// a variable product
$count_in_stock == 0;
$variation_ids = $product->get_children(); // Get product variation IDs
foreach( $variation_ids as $variation_id ){
$variation = wc_get_product($variation_id);
if( $variation->is_in_stock() )
$count_in_stock++;
}
}
if( $count_in_stock == 0 ) {
echo do_shortcode('[contact-form-7 id="304" title="Contact stock"]');
//echo "variable";
}
}
Try the following code, that will replace quantity field and add to cart button with a form when the product is "out of stock" (for all product types, including variable products).
You say "on simple products it still shows the 'variable' form": It's because you are using the same shortcode on both simple and variable products. So you will need to add the correct different shortcode for simple products.
The code:
add_action( 'woocommerce_single_product_summary', 'action_single_product_summary_callback', 4 );
function action_single_product_summary_callback() {
global $product;
// Variable products
if ( $product->is_type( 'variable' ) ){
$count_in_stock = 0;
foreach ( $product->get_visible_children() as $variation_id ) {
$variation = wc_get_product($variation_id);
if( $variation->is_in_stock() ) {
$count_in_stock++;
}
}
if ( $count_in_stock === 0 ) {
// Remove quantity field and add to cart button
remove_action( 'woocommerce_single_variation', 'woocommerce_single_variation_add_to_cart_button', 20 );
// Display the contact form
add_action( 'woocommerce_single_variation', 'display_variable_product_out_of_stock_form', 20 );
}
}
// Other products (Simple … )
else {
if ( ! $product->is_in_stock() ) {
// Remove quantity field and add to cart button
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
// Display the contact form
add_action( 'woocommerce_single_product_summary', 'display_simple_product_out_of_stock_form', 30 );
}
}
}
// Form for variable products
function display_variable_product_out_of_stock_form() {
echo do_shortcode('[contact-form-7 id="304" title="Contact stock"]');
}
// Form for Simple products
function display_simple_product_out_of_stock_form() {
echo do_shortcode('[contact-form-7 id="304" title="Contact stock"]'); // <== NOT the correct shortcode
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.

Set a custom calculated item price in Woocommerce mini-cart / Cart

Currently i have some custom calculation of product price based on different situation. When customer added a product in to cart then the custom price is set in session data , cart_item_data['my-price'] and i implemented using add_filter( 'woocommerce_add_cart_item') function and everything seems to working now .
Now the price in view cart page, checkout page is correct with my cart_item_data['my-price'].
But the only problem i am facing is the price is not updated in woocommerce mini cart that is appeared in the menu ,How can i change this ?
When i google i see a filter
add_filter('woocommerce_cart_item_price');
but i can't understand how to use this i do the following
add_filter('woocommerce_cart_item_price','modify_cart_product_price',10,3);
function modify_cart_product_price( $price, $cart_item, $cart_item_key){
if($cart_item['my-price']!==0){
$price =$cart_item['my-price'];
}
return $price;
//exit;
}
Here individual price is getting correct , but total price is wrong
Updated (october 2021)
For testing this successfully (and as I don't know how you make calculations), I have added a custom hidden field in product add to cart form with the following:
// 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
?>
<input type="hidden" id="my-price" name="my-price" value="115">
<?php
}
When product is added to cart, this my-price custom field is also submitted (posted). To set this value in cart object I use the following function:
add_filter( 'woocommerce_add_cart_item', 'custom_cart_item_prices', 20, 2 );
function custom_cart_item_prices( $cart_item_data, $cart_item_key ) {
// Get and set your price calculation
if( isset( $_POST['my-price'] ) ){
$cart_item_data['my-price'] = $_POST['my-price'];
// Every add to cart action is set as a unique line item
$cart_item_data['unique_key'] = md5( microtime().rand() );
}
return $cart_item_data;
}
Now to apply (set) the new calculated price my-price to the cart item, I use this last function:
// For mini cart *(cart item displayed price)*
add_action( 'woocommerce_cart_item_price', 'filter_cart_item_price', 10, 2 );
function filter_cart_item_price( $price, $cart_item ) {
if ( ! is_checkout() && isset($cart_item['my-price']) ) {
$args = array( 'price' => floatval( $cart_item['my-price'] ) );
if ( WC()->cart->display_prices_including_tax() ) {
$product_price = wc_get_price_including_tax( $cart_item['data'], $args );
} else {
$product_price = wc_get_price_excluding_tax( $cart_item['data'], $args );
}
return wc_price( $product_price );
}
return $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( isset( $cart_item['my-price'] ) && ! empty( $cart_item['my-price'] ) || $cart_item['my-price'] != 0 ){
// Set the calculated item price (if there is one)
$cart_item['data']->set_price( $cart_item['my-price'] );
}
}
}
All code goes in function.php file of your active child theme (or active theme).
Tested and works

woocommerce_before_calculate_totals fires twice

Writing an addition to the site, want to modify the price in the cart. Have the following code:
function apd_product_custom_price($cart_item_data, $product_id)
{
if (isset($_POST['use_rewards']) && !empty($_POST['use_rewards']))
{
$cart_item_data['use_rewards'] = $_POST['use_rewards'];
}
return $cart_item_data;
}
add_filter('woocommerce_add_cart_item_data', 'apd_product_custom_price', 99, 2);
function apd_apply_custom_price_to_cart_item($cart_object)
{
if( !WC()->session->__isset( 'reload_checkout' )) {
foreach ($cart_object->cart_contents as $value) {
if(isset($value['use_rewards'])) {
$price = $value['data']->get_price() -
$value['use_rewards'];
$value['data']->set_price($price);
}
}
}
}
add_action('woocommerce_before_calculate_totals', 'apd_apply_custom_price_to_cart_item',10);
By some reason the hook woocommerce_before_calculate_totals fires twice. if I replace the code in the function apd_apply_custom_price_to_cart_item($cart_object) with just echo 1; it displays 11 in the cart page. Can some please help?
I forgot the link I should refer to for a solution. You can use this at the top of your function:
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
Most likely some other plugins hooks to 'woocommerce_before_calculate_totals' action.
Try to disable plugins one by one and see witch one is causing this behaviour.
In my case I found that WooCommerce-multilingual plugin hooks to woocommerce_before_calculate_totals action.
So I did this:
add_action( 'woocommerce_before_calculate_totals', '_wm_ponc_upte_prc', 99 );
function _wm_ponc_upte_prc( $cart_object ) {
if ( !WC()->session->__isset( "reload_checkout" ) ) {
foreach ( WC()->cart->get_cart() as $key => $value ) {
// checking if user checked checkbox (optional)
if ( isset( $value['wm_ponc_fee'] ) && ( $value[ 'wm_ponc_fee' ] === 'yes' ) ) {
// your calculations ....
// and Remove your action after you are done.
remove_action( 'woocommerce_before_calculate_totals', '_wm_ponc_upte_prc', 99 );
}
}
}
}
I have removed action after custom calculations. And that's it.
I see exactly the same issue - my hooked function is firing twice, leading to the option price being added at 2x the cost. My solution was to load the product, get the price from that and then add my incremental cost to that.
function tbk_woo_update_option_price( $cart_object ) {
$option_price = 3.50;
foreach ( $cart_object->get_cart() as $cart_item_key => $cart_item ) {
$item_id = $cart_item['data']->id;
//Hook seems to be firing twice for some reason... Get the price from the original product data, not from the cart...
$product = wc_get_product( $item_id );
$original_price = $product->get_price();
$new_price = $original_price + $option_price;
$cart_item['data']->set_price( $new_price );
}
}
add_action( 'woocommerce_before_calculate_totals', 'tbk_woo_update_option_price', 1000, 1 );

I need help getting price changed woocoormerce from user input

How can I set a custom price based on user input? This custom price is hard coded. Any suggestions? Something like function add_custom_price( $cart_object, $custom_price )
<code>add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );
function add_custom_price( $cart_object,$custom_price ) {
$custom_price = $variable_from_input; // This will be my custom input variable
foreach ( $cart_object->cart_contents as $key => $value ) {
$value['data']->price = $custom_price;
}
}</code>

WooCommerce: Add product to cart with price override?

$replace_order = new WC_Cart();
$replace_order->empty_cart( true );
$replace_order->add_to_cart( "256", "1");
The above code add product 256 to the Cart 1 time. But the issue I'm having is that I want to be able to completely override the product price... as far as I can tell, the only thing I can do it apply a coupon to the Cart.
Is there a way to completely override the price to something totally custom?
Here is the code for overriding price of product in cart
add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );
function add_custom_price( $cart_object ) {
$custom_price = 10; // This will be your custome price
foreach ( $cart_object->cart_contents as $key => $value ) {
$value['data']->price = $custom_price;
// for WooCommerce version 3+ use:
// $value['data']->set_price($custom_price);
}
}
Hope it will be useful...
You need to introduce an if statement for checking product id, in above code:
add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );
function add_custom_price( $cart_object ) {
$custom_price = 10; // This will be your custome price
$target_product_id = 598;
foreach ( $cart_object->cart_contents as $value ) {
if ( $value['product_id'] == $target_product_id ) {
$value['data']->price = $custom_price;
}
/*
// If your target product is a variation
if ( $value['variation_id'] == $target_product_id ) {
$value['data']->price = $custom_price;
}
*/
}
}
Add this code anywhere and make sure that this code is always executable.
After adding this code, when you'll call:
global $woocommerce;
$woocommerce->cart->add_to_cart(598);
Only this product will be added with overridden price, other products added to cart will be ignored for overriding prices.
Hope this will be helpful.
I have tried all above code samples and latest woocommerce 3.0 is not support any of the above example. Use below code and working perfectly for me.
add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );
function add_custom_price( $cart_object ) {
$custom_price = 10; // This will be your custom price
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$cart_item['data']->set_price($custom_price);
}
}
After release of woocommerce version 3.0.0 product price is update on add to cart using set_price($price) function. The example is given as below :
add_action( 'woocommerce_before_calculate_totals', 'mj_custom_price' );
function mj_custom_price( $cart_object ) {
$woo_ver = WC()->version;
$custom_price = 10;
foreach ( $cart_object->cart_contents as $key => $value )
{
if($woo_ver < "3.0.0" && $woo_ver < "2.7.0")
{
$value['data']->price = $custom_price;
}
else
{
$value['data']->set_price($custom_price);
}
}
}
Many Thanks
For the Wordpress and Woocommerce latest version,Please use like this
add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );
function add_custom_price( $cart_object ) {
foreach ( $cart_object->cart_contents as $key => $value ) {
$custom_price = 5;
$value['data']->set_price($custom_price);
}
}
For eveeryone that got here from Google. The above is now deprecated as i found out updating to WooCommerce 3.0.1.
Instead of the above you now need to use set_price instead of price
Here is an example:
add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );
function add_custom_price( $cart_object ) {
$custom_price = 10; // This will be your custome price
foreach ( $cart_object->cart_contents as $key => $value ) {
$value['data']->set_price = $custom_price;
}
}
I hope this helps people in the future :)
This is how i did it, first i add my custom price to cart_item_data witch can save custom data to cart items, then i use woocommerce_before_calculate_totals, loop the cart and add the previously added price.
function add_donation_to_cart() {
$cart_item_data = array('price' => $_REQUEST['donate_amount']);
$woocommerce->cart->add_to_cart( 5395, 1, '', array(), $cart_item_data);
}
add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );
function add_custom_price( $cart ) {
foreach ( $cart->cart_contents as $key => $value ) {
$value['data']->price = $value['price'];
}
}
With WooCommerce 2.5 I found this to be a 2-part process. The first step is to change the run-time display of pricing when added to the cart via the woocommerce_add_cart_item filter. The second part is to set the persistent session data which is read during checkout via the woocommerce_get_cart_item_from_session filter. This seems to be faster than hooking the calculate totals filters (such as woocommerce_before_calculate_totals) as they are run very frequently in WooCommerce.
More details here:
woocommerce change price while add to cart
To make it dynamic ( override price for each item in cart separately ), you need to save the override product price in session with cart item key as session key using woocommerce_add_to_cart hook.
by using these session values you can calculate correct Cart Total and make the altered price appear in the Order Item as well
You can use the following
add_filter( 'woocommerce_cart_item_price', 'kd_custom_price_message' );
function kd_custom_price_message( $price ) {
$textafter = ' USD';
return $price . $textafter;
}

Categories