Recalculate Taxes in Woocommerce - php

I got a Problem. In Woocommerce I added a custom product type (abo), where the user can choose a area size (in square meters) and there is a price per square meter and a dosage information where it says e.g. "You need 0.165kg per squaremeter" (it´s a fertilizer).
So for example if the user chooses 100 square meters and the price per square meter is 2.30€ and the dosage is 0.165kg/sqm the total price of the abo is 37.95€ and at a tax rate of 10.7% the tax amount should be 4.06€.
My Problem now is, I have normal products in the shop as well, where the standard calculation of the price and tax etc. works perfectly fine and you can buy the abo and a normal product.
So my question is, how can I recalculate the tax amount if I got an abo in cart?
I tried a few things for testing so far:
Adding a custom fee (that isn´t what I´m looking for, cause the tax has to be the same on cart, checkout and receipt):
add_action( 'woocommerce_cart_calculate_fees','custom_tax_surcharge_for_swiss', 10, 1 );
function custom_tax_surcharge_for_swiss( $cart ) {
if(current_user_can('administrator')) :
$percent = 10.7;
// Calculation
$surcharge = ( $cart->cart_contents_total + $cart->shipping_total ) * $percent / 100;
// Add the fee (tax third argument disabled: false)
$cart->add_fee( __( 'TAX', 'woocommerce')." ($percent%)", $surcharge, false );
endif;
}
calc_tax function (I think this one is the one I need) :
/ define the woocommerce_calc_tax callback
function filter_woocommerce_calc_tax( $taxes, $price, $rates, $price_includes_tax, $suppress_rounding ) {
if(current_user_can('administrator')) :
foreach(WC()->cart->cart_contents as $item) :
if($item['data']->get_type() == 'abo') :
$qty = $item['quantity'];
$ppqm = str_replace(',', '.', get_post_meta($item['product_id'], 'abo_product_price_per_kg')[0]);
$kgpqm = str_replace(',', '.', get_post_meta($item['product_id'], 'abo_product_kg_qm')[0]);
$realQty = floatval($kgpqm) * floatval($qty);
$priceCustom = $priceCustom + $realQty * floatval($ppqm);
endif;
endforeach;
return $taxes;
};
// add the filter
add_filter( 'woocommerce_calc_tax', 'filter_woocommerce_calc_tax', 10, 5 );
With the above function I got the problem, that I don´t have the cart contents directly so it could be, that the order of the items isn´t the same as the Tax order which I get from the function.
I would also note, that the woocommerce_calc_tax fires twice. I had for debug reasons an output in the console and if I have 2 items in cart, I got 4 outputs.
Hope my Problem is clear and that anyone could help me with that problem.
Thanks in advance.

I would look into the tax class for WooCommerce. You can specific target a item with a different tax rate. Unless I'm missing something this should actually work how you need it to out of the box.
When checking out it will also separate the taxes.

Related

Can I change the order WooCommerce Coupons are applied programmatically?

I am developing a Woocommerce shop and want to offer all members (users logged in) 20% off their Total.
I have created a coupon called "twentypercent_off" and I am programmatically applying this using a custom function and a hook in my functions.php.
This works well.
In WC settings I have checked "Calculate coupon discounts sequentially" and this works almost as I would expect.
However what I would like is that my "twentypercent_off" is always applied last in cases where there are multiple coupons.
No matter what I have attempted to do (loop through all coupons on current order, remove all coupons, add them back in the order I desire) I find that Woo-commerce seems to always apply them in the order of monetary savings.
For example if the customer orders $100 worth of products and they have a coupon for $25 and also qualified to receive 20% off total.
I would like the total to calculate as (100 -25) * 0.8 = $60
but WC is calculating as such (100 * 0.8) - 25 = $55
I tried the following but it made no difference:
if ( is_user_logged_in() ) {
$Coupon_code = 'twentypercent_off';
$Current_Coupons = WC()->cart->get_coupons();
$Non_Prog_Coupons=array();
// loop through all current coupons
foreach( $Current_Coupons as $code => $coupon ){
if($code==$coupon_code){
WC()->cart->remove_coupon( $code );
} else {
WC()->cart->remove_coupon( $code );
$Non_Prog_Coupons[]=$code; // array of non-programmatically added coupons
}
}
// loop through non-programmatically added coupons
foreach( $Non_Prog_Coupons as $x => $code ){
WC()->cart->add_discount( $code ); // add them again
}
// add programmatically added coupon last !
WC()->cart->add_discount($Coupon_code);
}
return;
The only possible solution I have come across is to apply the 20% discount as a negative fee, which is not suitable for our purposes and would be an absolute last resort
Any ideas on how to achieve this would be greatly appreciated

Progressive fixed Coupon Discount based on specific product quantity in Woocommerce

I have one little problem that dont know how to fix myself. I want to use this logic into my Woocommerce store just for one product.
I have use link like this to autmatically apply coupon code and add to cart:
https://testsite.com/checkout/?add-to-cart=Product_ID&quantity=1&coupon=Coupon_Code
and this seems to work, when quantity is 1. But i want discount (30%) that is automatically placed when click on direct link from before, to make dynamic, for ex:
Increase quantity to 2 in cart page, and coupon automatically to calculate 2 x 30$ = 60$ discount,
buy 3 from same product, and calculate 3 X 30$ = 90$ coupon discount
and so on..
I searched, and found this usefull thread, but there situation is little different then mine.
How can I make to have a specific coupon? Some advice or start point. Thanks
This is possible with that 2 steps:
1) Add a unique coupon with:
In General settings > Type = Fixed Product discount
In General settings > Amount = 30
In Usage restrictions > Products ==> set your desired product(s)
2) Add this code (where you will set your coupon code in the function (in lowercase)):
add_filter( 'woocommerce_coupon_get_discount_amount', 'custom_coupon_get_discount_amount', 10, 5 );
function custom_coupon_get_discount_amount( $rounded_discount, $discounting_amount, $cart_item, $single, $coupon ){
## ---- Your settings ---- ##
// Related coupons codes to be defined in this array (you can set many)
$coupon_codes = array('30perqty');
## ------ The code ------- ##
if ( $coupon->is_type('fixed_product') && in_array( $coupon->get_code(), $coupon_codes ) && $cart_item['quantity'] > 1 ) {
if( in_array( $cart_item['product_id'], $coupon->get_product_ids() ) ){
$discount = (float) $coupon->get_amount() * (int) $cart_item['quantity'];
$round = round( min( $discount, $discounting_amount ), wc_get_rounding_precision() );
}
}
return $rounded_discount;
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.

How to show zero rate value of shipping class in cart page "WooCommerce"

I need some help in WooCommerce Shipping method. How can I show the value of shipping class on the cart page. Let me explain little bit my problem.
I added a flat rate to charge shipping for some products i.e. chairs €7 which is working perfect and show on cart page as => Shipping: Flat rate: €7 but I've some chairs to ship free to my customers. I added new class like "Free Shipping" and set the value to 0.00 EUR on checkout it's no charging any cost which fine, but when client view cart and in shipping it only show the name of shipping method like Flat Rate without any cost because that was set to 0.00 which doesn't convince the customer and he think we've hidden cost.
Is there any way to show the zero value of shipping class or is this possible to show the class name rather than shipping method's title?
You can add a filter, checking if the cost of your shipping method is zero (WooCommerce currently is doing nothing else in their function than printing the "flat rate" label, if the cost isn't above zero) and changing your label to whatever you'd like:
add_filter( 'woocommerce_cart_shipping_method_full_label', 'add_free_shipping_label', 10, 2 );
function add_free_shipping_label( $label, $method ) {
if ( $method->cost == 0 ) {
$label = 'Free shipping'; //not quite elegant hard coded string
}
return $label;
}
Based on https://stackoverflow.com/a/23581656/8264519 and works like a charm.
Thank you #DhirenPatel for your question. The following additional code works for the thank you page and email:
add_filter( 'woocommerce_order_shipping_to_display', 'add_free_shipping_label_email', 10, 2 );
function add_free_shipping_label_email( $label, $method ) {
if ( $method->cost == 0 ) {
$label = 'Free shipping'; //not quite elegant hard coded string
}
return $label;
}
Here is what I did.
1.Open \wp-content\plugins\woocommerce\includes\wc-cart-functions.php
2.Search for wc_cart_totals_shipping_method_label function
3.Replace if ( $method->cost > 0 ) with if ( $method->cost >= 0 ) and it should show the shipping cost even if it is set to 0.

How to add conditional price mark up in woocommerce?

I have been looking for this for a long time and can't seem to find an answer
I want to add mark up to my products based on their current price
e.g Products b/w £0-49 I want to £5
49-100 £10 and so on
But i want the markup to be part of the price displayed on shop and product page. (As In I don't want customer to see that I have added a markup)
any help will be appreciated.
Cheers
You can filter all the prices via woocommerce_get_price. Assuming that you want to add £5 for every £50 you could do something like:
function so_32352745_filter_price( $price ){
$factor = floor( $price / 50 );
$price = $price + $factor * 5;
return $price;
}
add_filter( 'woocommerce_get_price', 'so_32352745_filter_price' );

Woocommerce price after discount

I am not expert on WooCommerce, i cant find how to display price that calculate on it discount from coupon.
This code, display price after coupon, but also with shipping price - what i dont want, i want to display price after discount, before shipping and tax:
$woocommerce->cart->get_cart_total();
This code display the finnal price without discount and without shipping:
$woocommerce->cart->get_cart_subtotal();
So i tried something like that to get price after discount:
<?php
$totalp = $woocommerce->cart->get_cart_subtotal();
$totaldisc = $woocommerce->cart->get_total_discount();
$resultp = $totalp - $totaldisc;
echo ($resultp);
?>
But it show "0" number.
So, i guess there is simple function for what i want (i want to get total cart price after discount, before shipping), but i cant find this function.
Answer: i was need to use int's or floats without symbols, and the best way was to check WooCommerce docs here:
Woo - Docs , and to search for this variable and use it without () (not function). now it work :)
<?php
$first_number = $woocommerce->cart->subtotal;
$second_number = $woocommerce->cart->discount_total;
$sum_total = $first_number - $second_number;
print ($sum_total);
?>
Since you have the currency in the prices, you'll need to remove them.
I couldn't find WooCommerce code to just get the subtotal & discount without currency symbol, so let's just remove them manually:
function remove_currency($price) {
return (double) preg_replace('/[^0-9\.]+/', '', $price);
}
$totalp = remove_currency($woocommerce->cart->get_cart_subtotal());
$totaldisc = remove_currency($woocommerce->cart->get_total_discount());
$resultp = $totalp - $totaldisc;
echo $resultp;
This post is a bit old but I would like to inform anyone viewing that Woocommerce 3.x now uses:
WC()->cart
or you can use just
$cart
as long as you have the name_of_my_function( $cart ){} parameter callable.
Everything above is fine... I'm sure yet in hopes someone is not aware that $woocommerce global is no long in use.
There is also a way to loop foreach through the cart items (objects) to pick your price sub-totals using the cart_object.
foreach( $cart_obj->get_cart() as $key=>$value )
{
$priced = $value['subtotal'];
$new_price = $priced - ($predefined_referral_discount * 1);
$value['data']->set_price( $new_price );
}
Remember: name_of_my_function( $cart_obj ){} for this one.
Happy Coding

Categories