I'm having issues in Wordpress Woocommerce whereby I have programmatically updated prices of products based on whatever conditions they need. Below is a simple example. I have it displaying and then adding to the cart just fine. My problem is, when the user logs out and logs back in, the cart ends up returning the full prices of the product. Either I'm updating the price incorrectly, or there is a better way to ensure the cart has the correct discounted price.
Here is what I have in functions.php
add_action('woocommerce_get_price_html','pricechanger');
function pricechanger($price){
$theid = get_the_ID();
$product = wc_get_product($theid);
$price = $product->price;
$price = //do something to the price here
//save the productid/price in session for cart
$_SESSION['pd']['$theid'] = $price;
add_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10, 2);
add_action( 'init', 'woocommerce_add_to_cart_action', 10);
add_action( 'init', 'woocommerce_checkout_action', 10 );
return $price;
}
Because the price wouldn't transition to the add to cart button, I've had to save them in a session. I haven't found anywhere that sends that price to the cart.
add_action( 'woocommerce_before_calculate_totals', 'woo_add_discount');
function woo_add_discount() {
if(isset($_SESSION['pd'])) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
foreach($_SESSION['pd'] as $key => $val) {
if($cart_item['data']->id == $key){
$cart_item['data']->set_price($val);
}
}
}
}
}
Help is greatly appreciated!
Thanks!
I forgot to post my concluded answer here.
You need to run these hooks against your price change code:
add_action( 'woocommerce_before_calculate_totals', 'your_function_here');
add_action( 'woocommerce_before_mini_cart', 'your_function_here');
function your_function_here(){
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
//do something to your price here
$price = 'some calculation here';
//set your price
$cart_item['data']->price = floatval($price);
}
}
Hope that helps someone!
Related
I am trying to figure out a way to get the product ids of items that have their quantity reduced to 0 from the cart page.
I hook into the after woocommerce_after_cart_item_quantity_update which fires if user changes quantity to anything BUT 0. :(
function action_woocommerce_after_cart_item_quantity_update( $cart_item_key, $quantity, $old_quantity ) {
var_error_log([$cart_item_key, $quantity, $old_quantity]);
};
add_action( 'woocommerce_after_cart_item_quantity_update', 'action_woocommerce_after_cart_item_quantity_update', 10, 3 );
function var_error_log( $object=null ){
ob_start(); // start buffer capture
var_dump( $object ); // dump the values
$contents = ob_get_contents(); // put the buffer into a variable
ob_end_clean(); // end capture
error_log( $contents ); // log contents of the result of var_dump( $object )
}
Is there another way?
Edit:
Also the woocommerce_cart_item_removed hook is no good as it only runs when user clicks remove button, not when quantity for that item is changed to 0.
And the woocommerce_cart_item_removed hook occurs in a similar way to the woocommerce_cart_item_removed hook.
There is a seperate hook for this occurrence:
woocommerce_before_cart_item_quantity_zero
function woocommerce_before_cart_item_quantity_zero_vvvrbg45kt45($cart_item_key) {
global $woocommerce;
$cart_item = $woocommerce->cart->get_cart_item( $cart_item_key );
$product_id = $cart_item['product_id'];
}
add_action( 'woocommerce_before_cart_item_quantity_zero', 'woocommerce_before_cart_item_quantity_zero_vvvrbg45kt45' );
Try this hook,
add_action( 'woocommerce_cart_item_removed', 'after_remove_product_from_cart', 10, 2 );
function after_remove_product_from_cart($removed_cart_item_key, $instance) {
$line_item = $instance->removed_cart_contents[ $removed_cart_item_key ];
$product_id = $line_item[ 'product_id' ];
}
this will fire when an item is removed from the cart.
For more information,
woocommerce hook delete product from the cart
How to find out product id from “woocommerce_cart_item_removed” hook?
Hope this will helps you.
I am trying to change product price in cart using the following function:
add_action( 'woocommerce_before_shipping_calculator', 'add_custom_price'
);
function add_custom_price( $cart_object ) {
foreach ( $cart_object->cart_contents as $key => $value ) {
$value['data']->price = 400;
}
}
It was working correctly in WooCommerce version 2.6.x but not working anymore in version 3.0+
How can I make it work in WooCommerce Version 3.0+?
Thanks.
Update 2021 (Handling mini cart custom item price)
With WooCommerce version 3.0+ you need:
To use woocommerce_before_calculate_totals hook instead.
To use WC_Cart get_cart() method instead
To use WC_product set_price() method instead
Here is the code:
// Set custom cart item price
add_action( 'woocommerce_before_calculate_totals', 'add_custom_price', 1000, 1);
function add_custom_price( $cart ) {
// This is necessary for WC 3.0+
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Avoiding hook repetition (when using price calculations for example | optional)
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// Loop through cart items
foreach ( $cart->get_cart() as $cart_item ) {
$cart_item['data']->set_price( 40 );
}
}
And for mini cart (update):
// Mini cart: Display custom price
add_filter( 'woocommerce_cart_item_price', 'filter_cart_item_price', 10, 3 );
function filter_cart_item_price( $price_html, $cart_item, $cart_item_key ) {
if( isset( $cart_item['custom_price'] ) ) {
$args = array( 'price' => 40 );
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_html;
}
Code goes in functions.php file of your active child theme (or active theme).
This code is tested and works (still works on WooCommerce 5.1.x).
Note: you can increase the hook priority from 20 to 1000 (or even 2000) when using some few specific plugins or others customizations.
Related:
Set cart item price from a hidden input field custom price in Woocommerce 3
Change cart item prices based on custom cart item data in Woocommerce
Set a specific product price conditionally on Woocommerce single product page & cart
Add a select field that will change price in Woocommerce simple products
With WooCommerce version 3.2.6, #LoicTheAztec's answer works for me if I increase the priority to 1000.
add_action( 'woocommerce_before_calculate_totals', 'add_custom_price', 1000, 1);
I tried priority values of 10,99 and 999 but the price and total in my cart did not change (even though I was able to confirm with get_price() that set_price() had actually set the price of the item.
I have a custom hook that adds a fee to my cart and I'm using a 3rd party plugin that adds product attributes. I suspect that these WooCommerce "add-ons" introduce delays that require me to delay my custom action.
I have been overriding the price of products dynamically based on specific criteria, but the ajax and mini-cart doesn't seem to see the price change when the product is getting added in the cart. It shows the original price total. I can override the prices in the cart itself no problem, but you have to be on the cart or checkout page to see it. Not sure what approach to take. I felt as though I've tried everything.
Seems as though $woocommerce->cart->get_cart_total() is called to display current cart total, but it doesn't seem to run add_action( 'woocommerce_before_calculate_totals', 'woo_add_discount'); hook when called.
If you go to the actual cart page, it is the proper pricing.
This code added will display the right individual price but not the subtotal. You have to refresh the cart page by clicking on the Cart URL for it to update the $woocommerce->cart->get_cart_total() object.
I've also tried add_action( 'woocommerce_before_mini_cart', 'woo_add_discount'); which does the same thing.. you have to refresh the page after loading. I'm sure I'm not the only one who had overriden prices and can't get all the peices to fall into place.
I've tried this and see that the second comment down on the answer, someone is having the same issue but no answers.
WooCommerce: Add product to cart with price override?
Try to use apply_filters instead of add_action
I ended up fixing this myself. I tried Paul de Koning's answer. Changing to apply_filters caused the prices to go to $0. I think this is because the order they need to go in.
Here was my solution. The root cause was that I was using the change price_html function to provide the change prices for the cart. Inside that function there were add_action calls etc. Somehow, there must have been an ordering issue. This is a multi step process to ensure all areas are done correctly.
If you want to change woocommerce prices without using sessions to store the changed price for the cart while changing the display price and hiding prices, perform something like the following:
functions.php
add_action('woocommerce_get_price_html','special_price');
function special_price($price) {
//put any if statements for hiding the cart button and discounting pricing below and return true or false
$displayprice = true;
$alterprice = true;
if($displayprice === true) {
add_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10, 2);
add_action( 'init', 'woocommerce_add_to_cart_action', 10);
add_action( 'init', 'woocommerce_checkout_action', 10 );
} else {
remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10, 2);
remove_action( 'woocommerce_before_add_to_cart_form', 'woocommerce_template_single_product_add_to_cart', 10, 2); //
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price', 10 );
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
//return blank or something like 'Signup to view price'
return '';
}
//if you are displaying the price (altered)
if($displayprice === true && $alterprice === true){
$price = price_manipulator($theid);
return $price;
//display add to cart and price
}
//if you are displaying the price (unaltered)
return $price
}
function price_manipulator($theid = '') {
if(empty($theid)){
$theid = get_the_ID();
}
$product = wc_get_product($theid);
//30% off example
$newprice = floatval($product->price * (1-0.3));
return $newprice;
}
/*version of pricing if you are adding something to cart*/
function special_price_cart($theid){
$price = price_manipulator($theid);
return $price;
}
add_action( 'woocommerce_before_calculate_totals', 'woo_add_discount');
add_action( 'woocommerce_before_mini_cart', 'woo_add_discount'); //this is if you are using the mini-cart woocommerce widget
function woo_add_discount() {
global $woocommerce;
//create if statements same as if you were displaying the price
$displayprice = true;
if($displayprice === true){
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$price = special_price_cart($cart_item['data']->id);
$price = str_replace('$','',$price);
$price = str_replace(',','',$price);
if($price > 0){
$cart_item['data']->price = floatval($price);
}
}
}
}
I need to change the price of my products in my store, with a 10% discount, if my customer is from some specific place, so, I wrote this code:
add_filter('woocommerce_price_html', 'my_price_edit');
function my_price_edit() {
$product = new WC_Product( get_the_ID() );
$price = $product->price;
echo $price * 0.9;
}
Ok, it works! But when in the checkout the price are normals without the 10% discount!
Does have some hook for change the price of the products in the checkout area or some different code to change correctly in the both (in the product page and checkout)?
New in Woocommerce too.
Your question looks really similiar to this one.
Adding Custom price with woocomerce product price in Cart & Checkout
I think you need to use the woocommerce_cart_item_subtotal hook to change the price in the cart directly (not exactly as a parameter)
I made a slightly modification to the code (changed price formula). I think that may help you.
add_filter( 'woocommerce_get_discounted_price', 'calculate_discounted_price', 10, 2 );
// Display the line total price
add_filter( 'woocommerce_cart_item_subtotal', 'display_discounted_price', 10, 2 );
function calculate_discounted_price( $price, $values ) {
// You have all your data on $values;
$price = $price*.09;
return $price;
}
// wc_price => format the price with your own currency
function display_discounted_price( $values, $item ) {
return wc_price( $item[ 'line_total' ] );
}
I need to programmatically and dynamically change the price of an item in the cart.
I’ve tried varying combinations of Woocommerce action hooks, the cart and session objects, but nothing quite seems to do the trick. I thought this wouldn’t be so challenging.
add_action( 'woocommerce_before_calculate_totals', 'change_cart_item_price' );
function change_cart_item_price( $cart_object ) {
foreach ( $cart_object->cart_contents as $key => $value ) {
if( 123 == $value['data']->id ) {
$new_price = function_to_get_new_price( $value, get_current_user_id( ) );
$value['data']->price = $new_price;
}
}
}
The above code changes the price for each item only on the checkout page, or when updating the cart (ie: the hook is called when removing an item from the cart), but not indefinitely.
I'm using the Woocommerce Gravity Forms add-on. I have one product in particular, which will be ordered multiple times by a given user. The user will be allowed 5x free with only shipping fees, and each above 5 will be $20. I have this much coded and functional with Gravity Forms hooks that dynamically populate fields. Shipping is specific to fields within the gravity form, therefore I am leaving that calculation to Gravity Forms.
My issue is that if a user reduces the quantity of this product from their order (removes one of the items from the cart), it should re-calculate the price of each item of the same product within the cart, otherwise they could be over-charged (an item that used to be the 6th is now the 4th, but the price remains the same, which it shouldn't)
Therefore, I would like to re-calculate the price of each item in the cart, based on the quantity of this particular product, every time something is removed from the cart.
--- EDIT ---
The above code works, but I'm realizing the issue must be a custom loop I'm using to display the prices...
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$_product = $cart_item['data'];
if( 123 == $_product->post->ID ) {
$price_not_updated = $cart_item['data']->price;
}
}
I figured it out... I looked at the woocommerce cart docs and essentially realized that the prices I was getting had yet to be calculated. So, before running the loop, I had to do the action that I was initially hooking into to change the prices.
Thanks for your help!
function getUpdatedCartPrices() {
do_action( 'woocommerce_before_calculate_totals', WC()->cart );
$horray_updated_prices_works = array();
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$_product = $cart_item['data'];
if( 123 == $_product->post->ID ) {
$horray_updated_prices_works[] = $cart_item['data']->price;
}
}
}
I changed the function to have a second parameter so that you can use it dynamically with any product as long as you call the proper id. I also set the function return value to either a success or error message. This way you can know if it was changed, and if so, to what price. Hope this helps.
by the way, having this function called again when the cart is updated should solve the recalculation issue. It would be great if i could see the code for your $function_to_get_new_price() function.
add_action( 'woocommerce_before_calculate_totals', 'change_cart_item_price' );
function change_cart_item_price($id, $cart_object ) {
foreach ( $cart_object->cart_contents as $key => $value ) {
if( $id == $value['data']->id ) {
$new_price = function_to_get_new_price( $value, get_current_user_id( ) );
$value['data']->price = $new_price;
$successMsg = "The price of item $value['data']->id was set to $value['data']->price".;
return $successMsg;
}else{
$errorMsg = "Price was not changed!";
return $errorMsg;
}
}
}