woocommerce_before_calculate_totals hook not working properly - wordpress

I am using woocommerce_before_calculate_totals for adding extra price in woocommerce. If you add a product in cart and selected the price, the total price is correct in the checkout, but if the customer create his account in same process and checkout then the price is added twice after proced payment. This is my code
function calculate_gift_wrap_fee( $cart_object ) {
$additionalPrice = 100;
foreach ( $cart_object->cart_contents as $key => $value ) {
if( isset( $value["gift_wrap_fee"] ) ) {
$orgPrice = floatval( $value['data']->price );
$value['data']->price = ( $orgPrice + $additionalPrice );
}
}
}
Please help

If customer choose Create Account option at the time checkout, woocommerce calls calculate_totals() second time ( after customer account registered and auto logged them ) in order to recalculate cart totals to reveal any role-based discounts that were unavailable before registering.
So what you can do is check for "reload_checkout" session which will be set before calling calculate_totals() second time.
So update your calculate_gift_wrap_fee like this
function calculate_gift_wrap_fee( $cart_object ) {
if( !WC()->session->__isset( "reload_checkout" )) {
/* Gift wrap price */
$additionalPrice = 100;
foreach ( $cart_object->cart_contents as $key => $value ) {
if( isset( $value["gift_wrap_fee"] ) ) {
$orgPrice = floatval( $value['data']->price );
$value['data']->price = ( $orgPrice + $additionalPrice );
}
}
}
}
add_action( 'woocommerce_before_calculate_totals', 'calculate_gift_wrap_fee', 99 );

Related

Woocommerce restricted cart based on multiple product ID (problem with variations ID product)

I have problem to restrict cart based on multiple product ID, to be exact, with the variables product. I found the code online and try it out. The solutions seem to be okay with simple product.
The only problem is, how to include variations ID in product array? For example, I have two product ID, 1669 and 1694. 1694 is variable products, where it have 4 variations ID; 1769,1770, 1771 and 1772 while 1669 is simple product. When I click 1669(simple product) and add to cart, I cannot add 1694(variables product). I want to make it enable for ID 1694.
However, when i add to cart the variable product first (1694), then the 1669 can be add to cart. below is the code :
function aelia_get_cart_contents() {
$cart_contents = array();
/**
* Load the cart object. This defaults to the persistant cart if null.
*/
$cart = WC()->session->get( 'cart', null );
if ( is_null( $cart ) && ( $saved_cart = get_user_meta( get_current_user_id(), '_woocommerce_persistent_cart_' . get_current_blog_id(), true ) ) ) { // #codingStandardsIgnoreLine
$cart = $saved_cart['cart'];
}
elseif ( is_null( $cart ) ) {
$cart = array();
}
elseif ( is_array( $cart ) && ( $saved_cart = get_user_meta( get_current_user_id(), '_woocommerce_persistent_cart_' . get_current_blog_id(), true ) ) ) { // #codingStandardsIgnoreLine
$cart = array_merge( $saved_cart['cart'], $cart );
}
if ( is_array( $cart ) ) {
foreach ( $cart as $key => $values ) {
$_product = wc_get_product( $values['variation_id'] ? $values['variation_id'] : $values['product_id'] );
if ( ! empty( $_product ) && $_product->exists() && $values['quantity'] > 0 ) {
if ( $_product->is_purchasable() ) {
// Put session data into array. Run through filter so other plugins can load their own session data
$session_data = array_merge( $values, array( 'data' => $_product ) );
$cart_contents[ $key ] = apply_filters( 'woocommerce_get_cart_item_from_session', $session_data, $values, $key );
}
}
}
}
return $cart_contents;
}
// Step 1 - Keep track of cart contents
add_action('wp_loaded', function() {
// If there is no session, then we don't have a cart and we should not take
// any action
if(!is_object(WC()->session)) {
return;
}
global $allowed_cart_items;
global $restricted_cart_items;
$restricted_cart_items = array( 1669,1694) ;
// 1669 is simple product, 1694 is variable product
// "Snoop" into the cart contents, without actually loading the whole cart
foreach(aelia_get_cart_contents() as $item) {
if(in_array($item['data']->get_id(), $restricted_cart_items)) {
$allowed_cart_items[] = $item['data']->get_id();
// If you need to allow MULTIPLE restricted items in the cart, comment
// the line below
break;
}
}
// Step 2 - Make disallowed products "not purchasable"
add_filter('woocommerce_is_purchasable', function($is_purchasable, $product) {
global $restricted_cart_items;
global $allowed_cart_items;
// If any of the restricted products is in the cart, any other must be made
// "not purchasable"
if(!empty($allowed_cart_items)) {
// To allow MULTIPLE products from the restricted ones, use the line below
$is_purchasable = in_array($product->id, $allowed_cart_items) || in_array($product->id, $restricted_cart_items);
// To allow a SINGLE products from the restricted ones, use the line below
// $is_purchasable = in_array($product->get_id(), $allowed_cart_items);
}
return $is_purchasable;
}, 10, 2);
}, 10);
hope you guys can help me. thank you
to make sure those product (simple and variable products) can be add to cart together.

Add free product when a certain coupon is applied in WooCommerce

I can add a product to cart, when a certain coupon is used via the woocommerce_applied_coupon hook and the add_to_cart() function
add_action('woocommerce_applied_coupon', 'apply_product_on_coupon');
function apply_product_on_coupon( ) {
global $woocommerce;
$coupon_id = 'mybday';
$free_product_id = 131468;
if(in_array($coupon_id, $woocommerce->cart->get_applied_coupons())){
$woocommerce->cart->add_to_cart($free_product_id, 1);
}
}
My question: is there a way to also discount it to 0 in the same callback function?
Your current code contains some mistakes or could be optimized:
global $woocommerce can be replaced by WC()
$woocommerce->cart->get_applied_coupons() is not necessary, as the coupon that have been applied is passed to the callback function.
Instead, use the last available argument in WC_Cart::add_to_cart() method, which will allow you to add any custom cart item data. Then you will be able to get that data easily from the cart object.
So you get:
function action_woocommerce_applied_coupon( $coupon_code ) {
// Settings
$product_id = 131468;
$quantity = 1;
$free_price = 0;
$coupon_codes = array( 'coupon1', 'mybday' );
// Compare
if ( in_array( $coupon_code, $coupon_codes ) ) {
// Add product to cart
WC()->cart->add_to_cart( $product_id, $quantity, 0, array(), array( 'free_price' => $free_price ) );
}
}
add_action( 'woocommerce_applied_coupon', 'action_woocommerce_applied_coupon', 10, 1 );
// Set free price from custom cart item data
function action_woocommerce_before_calculate_totals( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) return;
// Loop through cart contents
foreach ( $cart->get_cart_contents() as $cart_item ) {
if ( isset( $cart_item['free_price'] ) ) {
$cart_item['data']->set_price( $cart_item['free_price'] );
}
}
}
add_action( 'woocommerce_before_calculate_totals', 'action_woocommerce_before_calculate_totals', 10, 1 );
Note: in addition to using woocommerce_applied_coupon, you must also use woocommerce_removed_coupon for when the coupon is removed, the product is removed as well
function action_woocommerce_removed_coupon( $coupon_code ) {
// Settings
$product_id = 131468;
$coupon_codes = array( 'coupon1', 'mybday' );
// Compare
if ( in_array( $coupon_code, $coupon_codes ) ) {
// Loop through cart contents
foreach ( WC()->cart->get_cart_contents() as $cart_item_key => $cart_item ) {
// When product in cart
if ( $cart_item['product_id'] == $product_id ) {
// Remove cart item
WC()->cart->remove_cart_item( $cart_item_key );
break;
}
}
}
}
add_action( 'woocommerce_removed_coupon', 'action_woocommerce_removed_coupon', 10, 1 );

Save value from a custom row added after the order table and display it in WooCommerce orders and emails

This code I wrote displays personalized information on the WooCommerce checkout page.
add_action( 'woocommerce_cart_totals_after_order_total', 'show_total_discount_cart_checkout', 9999 );
add_action( 'woocommerce_review_order_after_order_total', 'show_total_discount_cart_checkout', 9999 );
function show_total_discount_cart_checkout() {
$discount_total = 0;
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$product = $cart_item['data'];
$subtotal = WC()->cart->get_product_subtotal( $product, $cart_item['quantity'] );
$total = WC()->cart->total;
$pctm = 90.00;
$valor_descontado = $total - ($total / 100 * $pctm);
$sale_price = '10%';
$discount = ( WC()->cart->total - $valor_descontado );
$discount_total = $discount;
}
if ( $discount_total > 0 ) {
echo '<tr><th>VOCÊ RECEBERÁ DE CASHBACK:</th><td data-title="You">' . wc_price( $discount_total + WC()->cart->get_discount_total() ) .'</td></tr>';
}
}
The result:
I need this information to also be displayed in WooCommerce orders and emails. I believe I can come up with a solution myself to display this value on several other pages, but can someone first tell me how to save/store the value of this calculation?
First of all, I've rewritten your existing code for the following reasons:
Requesting subtotals and totals is best done outside the foreach loop, because otherwise these values ​​will be overwritten every time
The result of $subtotal is not used anywhere in your code
Since the result of $subtotal is not used anyway, loop through the cart seems unnecessary
$sale_price is also not used anywhere in your code
Since $discount_total = $discount it is not necessary to use a new variable
A session variable is created/added
Your existing code, but optimized:
function action_woocommerce_after_order_total() {
// WC Cart NOT null
if ( ! is_null( WC()->cart ) ) {
// Get cart
$cart = WC()->cart;
// Getters
$cart_total = $cart->total;
$cart_discount_total = $cart->get_discount_total();
// Settings
$pctm = 90;
// Calculations
$discounted_value = $cart_total - ( $cart_total / 100 * $pctm );
$discount_total = $cart_total - $discounted_value;
// Greater than
if ( $discount_total > 0 ) {
// Result
$result = $discount_total + $cart_discount_total;
// The Output
echo '<tr class="my-class">
<th>' . __( 'VOCÊ RECEBERÁ DE CASHBACK', 'woocommerce' ) . '</th>
<td data-title="You">' . wc_price( $result ) . '</td>
</tr>';
// Set session
WC()->session->set( 'session_result', $result );
}
}
}
add_action( 'woocommerce_cart_totals_after_order_total', 'action_woocommerce_after_order_total', 10 );
add_action( 'woocommerce_review_order_after_order_total', 'action_woocommerce_after_order_total', 10 );
To answer your question:
Step 1) We get the result from the session variable and add it as order data, so that we can use/obtain this information everywhere via the $order object
// Add as custom order meta data and reset WC Session variable
function action_woocommerce_checkout_create_order( $order, $data ) {
// Isset
if ( WC()->session->__isset( 'session_result' ) ) {
// Get
$result = (float) WC()->session->get( 'session_result' );
// Add as meta data
$order->update_meta_data( 'result', $result );
// Unset
WC()->session->__unset( 'session_result' );
}
}
add_action( 'woocommerce_checkout_create_order', 'action_woocommerce_checkout_create_order', 10, 2 );
Step 2) Use the woocommerce_get_order_item_totals filter hook, which will allow you to add a new row to the existing tables with the $result.
The new row will be added in:
Email notifications
Order received (thank you page)
My account -> view order
function filter_woocommerce_get_order_item_totals( $total_rows, $order, $tax_display ) {
// Get meta
$result = $order->get_meta( 'result' );
// NOT empty
if ( ! empty ( $result ) ) {
// Add new row
$total_rows['total_result']['label'] = __( 'VOCÊ RECEBERÁ DE CASHBACK', 'woocommerce' );
$total_rows['total_result']['value'] = wc_price( $result );
}
return $total_rows;
}
add_filter( 'woocommerce_get_order_item_totals', 'filter_woocommerce_get_order_item_totals', 10, 3 );

Add To Cart button Text Change Based on Discount

This will change the text into "Add again?" when the customer clicks "Add to cart" and I'm wondering how to change this into applying a discount each time the button is clicked.
Code:
add_filter( 'woocommerce_product_single_add_to_cart_text', 'woo_add_to_cart_again' );
function woo_add_to_cart_again() {
global $woocommerce;
foreach($woocommerce->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if( get_the_ID() == $_product->id ) {
return __('Add Again', 'woocommerce');
}
}
return __('Add to cart', 'woocommerce');
}
When clicked the first time, add to cart as normal but change the button text into "Buy again & Get 5% OFF", after pressed the 2nd time, text changes into "Buy 3 and get 10% OFF" and the discount should apply to the product, not the cart.
I would like for this to be a checkbox option beside "Downloadable" in WooCommerce Admin when creating a new product. Any help is highly appreciated.
first to change the text based on the quantity i just added an if condition to your function to check the quantity for that specific product in the cart and change the text accordingly as follow:
add_filter( 'woocommerce_product_single_add_to_cart_text', 'woo_add_to_cart_again' );
function woo_add_to_cart_again() {
global $woocommerce;
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $values['quantity'] == 1 && get_the_ID() == $_product->id ) {
return __( 'Buy again & Get 5% OFF', 'woocommerce' );
}
if ( $values['quantity'] == 2 && get_the_ID() == $_product->id ) {
return __( 'Buy 3 and get 10% OFF', 'woocommerce' );
}
if ( $values['quantity'] > 2 && get_the_ID() == $_product->id ) {
return __( 'Add Again', 'woocommerce' );
}
}
return __( 'Add to cart', 'woocommerce' );
}
Note: if you want to change the text in the archive page too you can use woocommerce_product_add_to_cart_text hook and added it to the above code as follow:
add_filter( 'woocommerce_product_single_add_to_cart_text', 'woo_add_to_cart_again' );
add_filter( 'woocommerce_product_add_to_cart_text', 'woo_add_to_cart_again' );
Then we need to calculate the price for those products which is qualified for the discount and add the discount based on the product prices.
We are going to use woocommerce_cart_calculate_fees to insert this discount to our cart as follow :
add_action( 'woocommerce_cart_calculate_fees', 'add_discount' );
function add_discount( WC_Cart $cart ) {
$discounts = []; //Store the disocunts in array
foreach ( $cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $values['quantity'] == 2 ) {
// Calculate the discount amount
$product_price = ( $_product->get_sale_price() ) ? $_product->get_sale_price() : $_product->get_regular_price();
$price = $product_price * 2;
array_push( $discounts, $price * 0.05 ); //Push the discount
}
if ( $values['quantity'] > 2 ) {
// Calculate the discount amount
$product_price = ( $_product->get_sale_price() ) ? $_product->get_sale_price() : $_product->get_regular_price();
$price = $product_price * $values['quantity'];
$discount = $price * 0.1;
array_push( $discounts, $price * 0.1 );//Push the discount
}
}
$cart->add_fee( 'Your Disocunt', -array_sum( $discounts ) );
}
Updated:
To Change the add_to_cart text when using Ajax actually it's already answered in here By #LoicTheAztec at this link and with little modification you can achieve your target goal as follow:
add_action( 'wp_footer', 'change_add_to_cart_jquery' );
function change_add_to_cart_jquery() {
if ( is_shop() || is_product_category() || is_product_tag() ) : ?>
<script type="text/javascript">
(function ($) {
$('a.add_to_cart_button').click(function () {
$this = $(this);
if (typeof $($this).attr('data-qty') == 'undefined') {
$($this).text('Buy again & Get 5% OFF');
$($this).attr('data-qty', 1);
return;
}
if ($($this).attr('data-qty') == 1) {
$($this).text('Buy 3 and get 10% OFF');
$($this).attr('data-qty', 2);
return
}
$($this).text('Add Again');
});
})(jQuery);
</script>
<?php
endif;
}
of course the code above has been tested.

How to change woocommerce price according to user input

I have used the hook woocommerce_before_calculate_totals but stuck in getting dynamic value in my function. Even i have used session but it didn't work on passing dynamic price.
The following snippet adds 100 to all the products in the cart, you can put your own conditions and pricing calculation there.
function calculate_product_price( $cart_object ) {
/* Gift wrap price */
$additionalPrice = 100;
foreach ( $cart_object->cart_contents as $key => $value ) {
//You can add your condition here
$quantity = floatval( $value['quantity'] );
$orgPrice = floatval( $value['data']->price );
$value['data']->price = ( ( $orgPrice + $additionalPrice ) * $quantity );
}
}
add_action( 'woocommerce_before_calculate_totals', 'calculate_product_price', 1, 1 );

Resources