Add a fee based on shipping method and payment method in Woocommerce - php

I need to apply an additional fee when a customer can place an order with free shipping, but wants to select COD payment.
So, Free Shipping + COD payment => fee.
I tried unsuccessfully the following piece of code. Where am I wrong?
add_action( 'woocommerce_cart_calculate_fees','cod_fee' );
function cod_fee() {
global $woocommerce;
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$chosen_gateway = WC()->session->chosen_payment_method;
$chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
$chosen_shipping = $chosen_methods[0];
$fee = 19;
if ( $chosen_shipping == 'free_shipping' && $chosen_gateway == 'cod' ) {
WC()->cart->add_fee( 'Spese per pagamento alla consegna', $fee, false, '' );
}
}

There is a mistake in your code and some additional code is needed. Try the following code that will add a specific fee when chosen payment method is Cash on delivery (cod) and when chosen shipping methods is "Free shipping":
// Add a conditional fee
add_action( 'woocommerce_cart_calculate_fees', 'add_cod_fee', 20, 1 );
function add_cod_fee( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
## ------ Your Settings (below) ------ ##
$your_payment_id = 'cod'; // The payment method
$your_shipping_method = 'free_shipping'; // The shipping method
$fee_amount = 19; // The fee amount
## ----------------------------------- ##
$chosen_payment_method_id = WC()->session->get( 'chosen_payment_method' );
$chosen_shipping_method_id = WC()->session->get( 'chosen_shipping_methods' )[0];
$chosen_shipping_method = explode( ':', $chosen_shipping_method_id )[0];
if ( $chosen_shipping_method == $your_shipping_method
&& $chosen_payment_method_id == $your_payment_id ) {
$fee_text = __( "Spese per pagamento alla consegna", "woocommerce" );
$cart->add_fee( $fee_text, $fee_amount, false );
}
}
// Refresh checkout on payment method change
add_action( 'wp_footer', 'refresh_checkout_script' );
function refresh_checkout_script() {
// Only on checkout page
if( is_checkout() && ! is_wc_endpoint_url('order-received') ) :
?>
<script type="text/javascript">
jQuery(function($){
// On payment method change
$('form.woocommerce-checkout').on( 'change', 'input[name="payment_method"]', function(){
// Refresh checkout
$('body').trigger('update_checkout');
});
})
</script>
<?php
endif;
}
Code goes in functions.php file of your active child theme (or active theme). tested and works.

Related

Cash On Delivery fee based on Dokan vendors count in WooCommerce

In WooCommerce Dokan multivendor shop I have Cash On Delivery (COD) payment for customers.
I created a code that counts the vendors in the cart and multiply them with the fee that i want per vendor. on my example is 2 € per vendor. so lets say that we have 1 product of each vendors(for now we have 2 vendors) on the cart. That should be 2 * 2 = 4€ total cost of COD.
That is working perfectly but when I received the order I see the fee only in main order and not in the suborders. it should be 2€ in one suborder and the other 2€ in the other suborder.
That has been working the whole time but since 11.02.2021 it suddenly stopped. Any ideas that could help me ?
Here is the code that I am using:
// 2 € Fee COD - Add a custom fee based on cart subtotal:
add_action( 'woocommerce_cart_calculate_fees', 'custom_fee_for_dokan', 999, 1 );
function custom_fee_for_dokan ( $cart ) {
$car_items = WC()->cart->get_cart(); // Cart items
$items_sort = array(); // Initializing
// Loop through cart items
foreach ( $car_items as $cart_item_key => $cart_item ) {
// Get the vendor_id
$vendor_id = get_post_field( 'post_author', $cart_item['product_id'] );
$store_info = dokan_get_store_info( $vendor_id ); // Get the store data
$store_name = $store_info['store_name']; // Get the store name
// Set in multidimentional array the vendor and then the cart item key
$items_sort[$store_name][$cart_item_key] = $vendor_id;
}
if ( count($car_items) > 1 ) {
ksort( $items_sort ); // Sorting by vendor name
}
$vendors = 0;
// Loop by vendor name
foreach ( $items_sort as $store_name => $values ) {
$vendor_id = reset($values); // The vendor id
$store_url = dokan_get_store_url( $vendor_id ); // Get the store URL (if needed)
$vendors++;
}
// End of Loop
$flatrate = $vendors * 2;
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( ! ( is_checkout() && ! is_wc_endpoint_url() ) )
return; // Only checkout page
$payment_method = WC()->session->get( 'chosen_payment_method' );
if ( 'cod' == $payment_method ) {
// $surcharge == $vendors;
$cart->add_fee( 'Pay on delivery', $flatrate , true );
}
}
// jQuery - Update checkout on methode payment change
add_action( 'wp_footer', 'nik_checkout' );
function nik_checkout() {
if ( ! ( is_checkout() && ! is_wc_endpoint_url() ) )
return; // Only checkout page
?>
<script type="text/javascript">
jQuery( function($){
$('form.checkout').on('change', 'input[name="payment_method"]', function(){
$(document.body).trigger('update_checkout');
});
});
</script>
<?php
}
The issue is related to Dokan plugin that does not split the fee by suborders anymore in the plugin recent versions. So you should ask Dokan support, to check if it's not a bug introduced on last updates or if it's not a new available setting.
Now your code is outdated and complicated for nothing. It can really be simplified and optimized.
The following code will set a COD fee based on dokan vendors count:
// COD Fee based on vendors count
add_action( 'woocommerce_cart_calculate_fees', 'dokan_cod_fee_vendors_based' );
function dokan_cod_fee_vendors_based ( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Only checkout page
if ( ! ( is_checkout() && ! is_wc_endpoint_url() ) )
return;
$fee_by_vendor = 2; // HERE set the fee by vendor
$vendors_array = array(); // Initializing
// Loop through cart items
foreach ( $cart->get_cart() as $item ) {
$vendor_id = get_post_field('post_author', $item['product_id']); // Get the vendor_id
// Set in an indexed array to get how many vendors
$vendors_array[$vendor_id] = $vendor_id;
}
$fee_total = count($vendors_array) * $fee_by_vendor; // Get fee total by vendor
if ( 'cod' === WC()->session->get( 'chosen_payment_method' ) ) {
$cart->add_fee( 'Cash On Delivery Fee', $fee_total, true ); // Apply the fee
}
}
// jQuery - Update checkout on methode payment change
add_action( 'wp_footer', 'payment_refresh_checkout_js' );
function payment_refresh_checkout_js() {
// Only checkout page
if ( ! ( is_checkout() && ! is_wc_endpoint_url() ) )
return; // Exit
?>
<script type="text/javascript">
jQuery( function($){
$('form.checkout').on('change', 'input[name="payment_method"]', function(){
$(document.body).trigger('update_checkout');
});
});
</script>
<?php
}
Code goes in functions.php file of the active child theme (or active theme). It should works.

Auto apply / remove a coupon code based on cart items in Woocommerce

I wanted to apply a coupon code to cart if cart have minimum 2 items. if not have then the coupon not will apply and show alter message and if have apply then will show a success message here is my code I have tried not working like I want
add_action( 'woocommerce_before_calculate_totals','conditionally_auto_add_coupon', 30, 1 );
function conditionally_auto_add_coupon( $cart ) {
if ( is_admin() && !defined('DOING_AJAX') ) return; // Exit
// HERE set the coupon code (in lowercase)
$coupon_code = 'mycode';
$total_item = 0;
if (WC()->cart->has_discount('mycode')) {
foreach( $cart->get_cart() as $cart_item ){
$total_item++;
}
if($total_item < 2){
$cart->remove_coupon( $coupon_code );
wc_add_notice( __('you have only 1 item in cart'), 'alert');
}
else{
$cart->add_discount( $coupon_code );
wc_add_notice( __('coupon added'), 'notice');
}
}
}
Any help is welcome.
Try the following:
add_action( 'woocommerce_before_calculate_totals', 'auto_apply_coupon_conditionally', 10, 1 );
function auto_apply_coupon_conditionally( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
$coupon_code = 'summer'; // HERE set the coupon code (in lowercase)
$applied = in_array( $coupon_code, $cart->get_applied_coupons() ) ? true : false;
$item_count = sizeof( $cart->get_cart() );
$total_item = 0;
// Remove coupon
if ( $item_count < 2 && $applied ) {
$cart->remove_coupon( $coupon_code );
wc_clear_notices();
wc_add_notice( __('You have only 1 item in cart'), 'error');
}
// Add coupon
elseif ( $item_count >= 2 && ! $applied ) {
$cart->apply_coupon( $coupon_code );
wc_clear_notices();
wc_add_notice( __('A coupon has been added'), 'notice' );
}
}
Code goes in function.php file of your active child theme (or active theme). Tested and works
Please use "Smart Coupon For Woocommerce" plugin implementing the auto coupon functionality,
Please refer this code in svn repo.

Applied coupons disable Free shipping conditionally in Woocommerce

I am trying to get it so that if a customer were to add a coupon code (Any of them) the Free Shipping option would go away and the flat rate fee would be implemented. - You would think this would be an easy thing to implement, there would be 100's of plugins and ways described to do this, but I have not found any. I do not want to pay $89 for the plugin to do this one thing
A side bonus would be if they are using a coupon but are spending over $249 they can still qualify for Free shipping. I read some where how to do this, but it requires me to get the POST ID, which with the latest WooCommerce is not possible like it was before, I do not know the shipping ID so I am at a lost Here is the code
add_filter( 'woocommerce_shipping_packages', function( $packages ) {
$applied_coupons = WC()->session->get( 'applied_coupons', array() );
if ( ! empty( $applied_coupons ) ) {
$free_shipping_id = 'free_shipping:2';
unset($packages[0]['rates'][ $free_shipping_id ]);
}
return $packages;
} );
Thanks
Edited
add_filter( 'woocommerce_package_rates', 'coupons_removes_free_shipping',
10, 2 );
function coupons_removes_free_shipping( $rates, $package ){
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return $rates;
$min_total = 250; // Minimal subtotal allowing free shipping
// Get needed cart totals
$total_excl_tax = WC()->cart->get_total();
$discount_excl_tax = WC()->cart->get_discount_total();
// Calculating the discounted subtotal including taxes
$discounted_subtotal_incl_taxes = $total_excl_tax - $discount_excl_tax;
$applied_coupons = WC()->cart->get_applied_coupons();
if( sizeof($applied_coupons) > 0 && $discounted_subtotal_incl_taxes < $min_total ) {
foreach ( $rates as $rate_key => $rate ){
// Targeting "Free shipping"
if( 'free_shipping' === $rate->method_id ){
unset($rates[$rate_key]);
}
}
}
return $rates;
}
The below code will enable "Free shipping" for applied coupons only if cart subtotal reaches a minimal amount (discounted including taxes):
add_filter( 'woocommerce_package_rates', 'coupons_removes_free_shipping', 10, 2 );
function coupons_removes_free_shipping( $rates, $package ){
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return $rates;
$min_subtotal = 250; // Minimal subtotal allowing free shipping
// Get needed cart subtotals
$subtotal_excl_tax = WC()->cart->get_subtotal();
$subtotal_incl_tax = $subtotal_excl_tax + WC()->cart->get_subtotal_tax();
$discount_excl_tax = WC()->cart->get_discount_total();
$discount_incl_tax = $discount_total + WC()->cart->get_discount_tax();
// Calculating the discounted subtotal including taxes
$discounted_subtotal_incl_taxes = $subtotal_incl_tax - $discount_incl_tax;
$applied_coupons = WC()->cart->get_applied_coupons();
if( sizeof($applied_coupons) > 0 && $discounted_subtotal_incl_taxes < $min_subtotal ){
foreach ( $rates as $rate_key => $rate ){
// Targeting "Free shipping"
if( 'free_shipping' === $rate->method_id ){
unset($rates[$rate_key]);
}
}
}
return $rates;
}
Code goes in function.php file of your active child theme (or active theme). Tested and work.
Original answer:
The below code will remove "Free shipping" shipping methods when any coupon is applied without any settings need. There is some mistakes in your actual code. Try the following:
add_filter( 'woocommerce_package_rates', 'coupons_removes_free_shipping', 10, 2 );
function coupons_removes_free_shipping( $rates, $package ){
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return $rates;
$applied_coupons = WC()->cart->get_applied_coupons();
if( sizeof($applied_coupons) > 0 ){
// Loop through shipping rates
foreach ( $rates as $rate_key => $rate ){
// Targeting "Free shipping" only
if( 'free_shipping' === $rate->method_id ){
unset($rates[$rate_key]); // Removing current method
}
}
}
return $rates;
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
By default WooCommerce will still allow a free shipping method to be selected if the coupon code is filled in and active in the shopping cart. The following code can be added to your child’s functions.php page to hook in and hide any free shipping option if a coupon code is used.
add_filter( 'woocommerce_shipping_packages', function( $packages ) {
$applied_coupons = WC()->session->get( 'applied_coupons', array() );
if ( ! empty( $applied_coupons ) ) {
$free_shipping_id = 'free_shipping:2';
unset($packages[0]['rates'][ $free_shipping_id ]);
}
return $packages;
} );
Simply change the $free_shipping_id in the above code to the ID of your free shipping option. You may find your ID by going to WooCommerce > Settings > Shipping Options and then click on your Free Shipping option. The post ID will be in the URL of the page that displays the Free Shipping details/settings.
i.e www.yourdomain.com/wp-admin/post.php?post=40107&action=edit
Where 40107 is the shipping ID in this example. Your shipping ID will be different.

Add a calculated fee based on total after discounts in WooCommerce

I'm trying to add a fee to my woocommerce cart based on the subtotal after discounts have been applied:
add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_surcharge' );
function woocommerce_custom_surcharge() {
global $woocommerce;
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$percentage = 0.01;
$surcharge = $woocommerce->cart->subtotal - $woocommerce->cart->get_cart_discount_total();
$woocommerce->cart->add_fee( 'Surcharge', $surcharge, true, '' );
}
I don't believe calls like $woocommerce->cart->get_cart_discount_total() can be used in an action hook, which is why I keep getting 0.00 for the fee.
I also read around some WC values are deprecated and will always show zero, but it doesn't explain why those amounts appear in filters and not actions.
What else can I use in an action to get the same number and add a percent fee to?
The WC_Cart object argument is included in woocommerce_cart_calculate_fees action hook. I also use the percentage amount calculation, as I suppose you just forgot it in your code.
So you should try this instead:
add_action( 'woocommerce_cart_calculate_fees','wc_custom_surcharge', 10, 1 );
function wc_custom_surcharge( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// HERE set your percent rate
$percent = 1; // 1%
// Fee calculation
$fee = ( $cart->subtotal - $cart->get_cart_discount_total() ) * $percent / 100;
// Add the fee if it is bigger than O
if( $fee > 0 )
$cart->add_fee( __('Surcharge', 'woocommerce'), $fee, true );
}
Code goes in function.php file of your active child theme (or theme).
Tested and works perfectly.
Note: Also global $woocommerce; with $woocommerce->cart has been replaced by WC()->cart since a long time. The WC() woocommerce object already include itself global $woocommerce;…
Specific update:
add_action( 'woocommerce_cart_calculate_fees','wc_custom_surcharge', 10, 1 );
function wc_custom_surcharge( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// HERE set your percent rate and your state
$percent = 6;
$state = array('MI');
$coupon_total = $cart->get_discount_total();
// FEE calculation
$fee = ( $cart->subtotal - $coupon_total ) * $percent / 100;
if ( $fee > 0 && WC()->customer->get_shipping_state() == $state )
$cart->add_fee( __('Tax', 'woocommerce'), $fee, false);
}
Code goes in function.php file of your active child theme (or theme).
Tested and works.
the plugin i was using to create coupons was hooking into after_calculate_totals and adjusting the amount afterwards. anything that fires before the plugin wasn't counted into that adjusted total. i was able to call specific amounts using variables in the plugin to create the fee amount i needed
for anyone else who is interested: i am using the ignitewoo gift certificates pro plugin and wanted to create a fee based on the remaining balance after coupons. this is Loic's code with some modifications:
add_action( 'woocommerce_cart_calculate_fees','wc_custom_surcharge', 10, 1 );
function wc_custom_surcharge( $cart) {
global $woocommerce;
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$state = array('MI');
// HERE set your percent rate
$percent = 6;
$coupTotal = 0;
foreach ( $woocommerce->cart->applied_coupons as $cc ) {
$coupon = new WC_Coupon( $cc );
$amount = ign_get_coupon_amount( $coupon );
$coupTotal += $amount;
}
// Fee calculation
$fee = ($cart->subtotal - $coupTotal) * $percent/100;
if (( $fee > 0 ) AND (in_array( WC()->customer->shipping_state, $state ) ))
$cart->add_fee( __('Tax', 'woocommerce'), $fee, false);
}

Custom woocommerce cart surcharge depending on products kind (non pdf)

In WooCommerce, I am using the code below to add a $12 surcharge to sales for Canadian Customers in the functions.php file of the child theme for one of my client.
But I need to remove the charge for all pdf downloads.
Is this possible altering the code I used?
Here is my code:
add_action( 'woocommerce_cart_calculate_fees','xa_add_surcharge' );
function xa_add_surcharge() {
global $woocommerce;
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$county = array('CA');
$fee = 12.00;
if ( in_array( $woocommerce->customer->get_shipping_country(), $county ) ) :
$surcharge = + $fee;
$woocommerce->cart->add_fee( 'Surcharge for International Orders', $surcharge, true, '' );
endif;
}
It's possible checking in cart items for non downloadable product (or depending ion your PDF products settings for non virtual products).
Additionally I have revisited your code a bit:
add_action( 'woocommerce_cart_calculate_fees','add_custom_surcharge', 10, 1 );
function add_custom_surcharge( $wc_cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
$countries = array('CA'); // Defined countries
// Continue only for defined countries
if( ! in_array( WC()->customer->get_shipping_country(), $countries ) ) return;
$fee_cost = 12; // The Defined fee cost
$downloadable_only = true;
// Checking cart items for NON downloadable products
foreach ( $wc_cart->get_cart() as $cart_item_key => $cart_item ) {
// Checks if a product is not downloadable.
if( ! $cart_item['data']->is_downloadable( ) ){ // or cart_item['data']->is_virtual()
$downloadable_only = false;
break;
}
}
// If one product is not downloadable and if customer shipping country is Canada we add the fee
if ( ! $downloadable_only )
$wc_cart->add_fee( "Surcharge for International Orders", number_format( $fee_cost, 2 ), true );
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
All code is tested on Woocommerce 3+ and works.

Categories