One of the reasons WooCommerce is the most popular eCommerce platform is the wide flexibility it offers. And because of its popularity, if you want to get your hands a little dirty there is always a free solution for whatever you want to accomplish. In this little tutorial we will learn how to add both fixed and conditional custom rates and fees to your Woocommerce shopping cart.
For example, we can set a fee if the cart exceeds a certain amount, or there are too few products within it. On my site this logic is used to charge customers the stamp fee if the amount of 77.47€ is exceeded
As extensively explained in the article speed up wordpress I am against the approach of installing a plugin for every additional feature you want to achieve. This is precisely why we will take a different approach by adding a few lines of code to the theme.
Working with the function.php file in Wordpress
Before we start with adding the rates, we need to make some premises about adding custom code to Wordpress. In order to achieve the result we will in fact have to fiddle with the function.php, and it is an extremely delicate operation. So you have to arm yourself with patience and follow all the security steps so that you don't end up with an unusable site, or even worse lose data.
To make changes to the file functions.php of WordPress, it is important to proceed with caution to avoid mistakes that could make your site inaccessible. Here is a step-by-step guide to doing this safely.
Safety tips:
- Use a child theme: To avoid losing your customizations when you update the theme, it is advisable to make changes in a child theme instead of the main theme.
- Document the changes: Keep track of changes made to the functions.php file, so that you can easily restore or modify them in the future.
By following these steps, you can safely and efficiently edit the functions.php file of your WordPress theme, expanding the functionality of your site.
1. Backing up the site
Before making any changes, it is essential to make a full backup of your WordPress site. This allows you to restore the site to its original condition in case of errors.
Without going into too much detail, a foolproof backup strategy is the 3-2-1 strategy. Three separate backup copies of which two are kept on as many different devices, plus one copy kept in a different location.
For my hosting service I keep the three copies in the datacenter, in the office, and in encrypted cloud storage.
2. Access to the functions.php file.
The functions.php file is located in the folder of the theme you are using. You can access it in several ways:
- Via FTP: Use an FTP client to access your site's files. Find the wp-content/themes/theme-name folder and open the functions.php file.
- From the WordPress admin panel: Go to Appearance > Theme Editor. Select the theme you are editing from the list on the right and look for the functions.php file in the list of theme files.
3. Editing the functions.php file.
- Important advice: It is recommended that you add your customizations to the end of the functions.php file to avoid conflicts with existing theme functionality.
- Use a text editor to make the necessary changes. If you are using the WordPress editor, you will have a text area where you can enter your code.
- Make sure your code is correct and contains no syntax errors. Even a small error can cause problems for your site.
4. Save changes
After making the changes, save the file. If you're using an FTP client, save the modified file to your computer and then upload it to the server, overwriting the existing version. If you are using the WordPress editor, simply click on "Update File."
5. Verify changes
Once you have saved your changes, visit your site to make sure everything is working as expected. If you encounter errors, check the code you added to identify and correct any problems.
Safety tips:
- Use a child theme: To avoid losing your customizations when you update the theme, it is advisable to make changes in a child theme instead of the main theme.
- Document the changes: Keep track of changes made to the functions.php file, so that you can easily restore or modify them in the future.
By following these steps, you can safely and efficiently edit the functions.php file of your WordPress theme, expanding the functionality of your site.
Adding an additional fee to the Woocommerce shopping cart
Having said all that has been said about backup and security, it is time to get our hands dirty. We will mostly use these functions:
- The function
calculate_fees()
- The function
add_fee()
- The action
woocommerce_cart_calculate_fees
- The class
WC_Cart
Additional rate based on a custom field
Adding custom fields to products can significantly improve customer loyalty and sales by providing essential product information. Here's how you can add custom rates to a shopping cart based on the value of a product's custom field in WordPress using WooCommerce.
To do this, you have to write some custom code in the functions.php
of your theme (or child theme, which is the recommended practice). Below is sample code demonstrating how to implement this functionality:
function aggiungi_tariffa_personalizzata_al_carrello( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
$tariffa_aggiuntiva = 0; // Inizializza la tariffa aggiuntiva a 0
// Ciclo attraverso tutti i prodotti nel carrello
foreach ( $cart->get_cart() as $cart_item ) {
$valore_meta_prodotto = isset( $cart_item['data']->get_meta('il_tuo_campo_personalizzato')[0] ) ? $cart_item['data']->get_meta('il_tuo_campo_personalizzato')[0] : '';
// Qui puoi implementare la tua logica per aggiungere la tariffa basata sul valore del campo personalizzato
// Ad esempio, aggiungi una tariffa fissa se il campo personalizzato ha un certo valore
if ( $valore_meta_prodotto === 'ValoreSpecifico' ) {
$tariffa_aggiuntiva += 5; // Aggiungi 5 euro (o qualsiasi valuta tu stia usando) di tariffa per questo prodotto
}
}
// Se la tariffa aggiuntiva è maggiore di 0, aggiungila al carrello
if ( $tariffa_aggiuntiva > 0 ) {
$cart->add_fee( 'Tariffa Personalizzata', $tariffa_aggiuntiva );
}
}
add_action( 'woocommerce_cart_calculate_fees', 'aggiungi_tariffa_personalizzata_al_carrello' );
Please note:
- You need to replace
'your_custom_field'
with the actual identifier of the custom field you intend to verify. - Edit
'ValueSpecific'
with the value of the custom field you are looking for. - The quantity
5
is the amount of the fee you want to add. You can change this value according to your needs. 'Customized Rate'
is the name that will be displayed in the cart and checkout summary for this rate. Feel free to change it to something more descriptive for your customers.
This solution allows you to add custom rates to the shopping cart based on product custom field values, providing greater flexibility in handling various needs and improving the shopping experience for your customers.
Additional fee based on product category
To add a rate to the cart based on the category of a product in WooCommerce, you can use the following code in the file functions.php
Of your theme or child theme. This snippet checks if there are products in the cart that belong to a certain category and, if so, adds a handling fee to the cart total.
function add_tariff_by_product_category( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
$category_target = 'delicate'; // Replace with the slug of your category
$tariff_additive = 5; // Set the amount of the additional tariff
$ariff_name = "Management tariff"; // The name that will appear in the shopping cart
$rue = false;
// Checks each product in the cart to see if it belongs to the specified category
foreach ( $cart->get_cart() as $cart_item ) {
$product = $cart_item['data'];
if ( has_term( $cart_target, 'product_cat', $product->get_id() ) ) {
$rue = true;
break; // Exit the loop once the first product in the target category is found
}
}
// If a product was found in the category, adds the rate to the cart
if ( $found ) {
$cart->add_fee( $ariff_name, $tariff_add );
}
}
add_action( 'woocommerce_cart_calculate_fees', 'add_tariff_by_product_category', 20, 1 );
How this code works:
- Set the
slug
of the product category of interest in the variable$arget_category
. - Defines the amount of the additional fee in the variable
1TP4Additional_rate
. - The cycle
foreach
scrolls through all the products in the shopping cart, usinghas_term
to check whether the product belongs to the specified category. - If there is at least one product in the specified category in the shopping cart, the function
add_fee
is used to add the specified rate to the cart total.
Remember to replace 'delicate'
with the slug of the product category for which you wish to add the tariff and to adjust the tariff amount (1TP4Additional_rate
) and the name of the tariff ($ariff_name
) according to your needs. This approach allows you to cover additional costs specific to certain product categories, such as those related to handling delicate items.
Additional fee based on payment method
To add a custom rate to the shopping cart based on the payment gateway selected by the user in WooCommerce, you can use the following code. This snippet should be placed in the functions.php
of your WordPress theme. The code allows you to charge an additional fee based on the payment method chosen by the customer, for example, to cover payment gateway transaction fees such as PayPal or to incentivize the use of preferred payment methods.
function add_tariff_gateway_payment( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
$chosen_payment_method = WC()->session->get( 'chosen_payment_method' );
$tariff = 0;
$ariff_name = "";
switch ( $chosen_payment_method ) {
case 'paypal':
$name_tariff = "PayPal commission";
$ariff = 0.034; // 3.4% of the cart total
break;
case 'bacs': // Bank transfer
$ariff_name = "Bank Transfer Commission";
$ariff = 2; // Fixed rate, e.g., 2 euro
break;
// Add other payment gateways here if necessary
}
if ( $ariff > 0 ) {
$total = $cart->cart_contents_total + $cart->shipping_total;
$cart->add_fee( $cart_name, $total * $tariff, true );
}
}
add_action( 'woocommerce_cart_calculate_fees', 'add_tariff_gateway_payment', 20, 1 );
Note:
- The code shown above is an example that includes PayPal with a 3.4% fee of the cart total and wire transfer (BACS) with a fixed rate. You can change these fixed rates/fees and add other payment methods by editing the code in the
switch
. - The line
$total = $cart->cart_contents_total + $cart->shipping_total;
calculates the cart total by including both the cost of the products and the shipping charges, on which it then applies the commission percentage. For fixed rates, this line is not necessary, but has been included for completeness. - Remember to replace the example values with the actual fees you intend to charge for each payment method.
This approach allows you to pass on the costs of transaction fees to the customer, incentivizing the use of more advantageous payment methods for you as a seller, and could help improve the overall profitability of your online store.
Additional fee based on the amount spent
To incentivize customers to reach a minimum spend amount and be able to charge a handling fee for orders below a certain threshold, you can use the following code. This snippet should be inserted into the functions.php
of your WordPress theme. It automatically adds a fee to your cart if the total order amount is less than a certain amount, for example $100.
function add_basic_rate_on_minimum_truck_amount( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
$minimum_amount = 100; // Set the minimum amount to avoid the tariff
$tariff_additive = 10; // Set the tariff amount for orders below the minimum amount
$total_cart = $cart->cart_contents_total;
if ( $total_cart add_fee( 'Management Fee for Orders Less than $100', $tariff_add_total );
}
}
add_action( 'woocommerce_cart_calculate_fees', 'add_basic_rate_on_minimum_cart_amount', 20, 1 );
This code checks if the cart total (excluding tax and shipping) is less than the specified minimum amount ($100 in the example). If so, it applies an additional charge of $10 (or whatever amount you specify) to the cart. You can change the minimum amount $minimum_amount
and the rate 1TP4Additional_rate
According to your needs.
This strategy may incentivize customers to spend more to avoid the fee, potentially increasing the average order value on your site. However, it is important to clearly communicate this policy on your site to avoid surprises from customers and ensure that the shopping experience remains positive.
Instead, use a maximum amount
To add an additional fee to a customer's cart based on the maximum cart amount, you can use the following code. This approach can be useful in situations where there are additional charges for processing large orders. Sometimes, payment processors may also charge a higher fee for processing a larger amount. In that case, you can pass these additional costs on to customers by adding an additional fee to their cart based on the maximum cart amount. Here's how you can do this by inserting the following snippet into the functions.php
Of your WordPress theme:
function add_basic_rate_on_maximum_truck_amount( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
$max_amount = 500; // Set the maximum amount before the tariff is applied
$tariff_additional_amount = 20; // Set the tariff amount for orders above the maximum amount
$total_cart = $cart->cart_contents_total;
if ( $total_cart > $max_amount ) {
$cart->add_fee( 'Management Fee for Orders Greater than $500', $tariff_add_total );
}
}
add_action( 'woocommerce_cart_calculate_fees', 'add_basic_fee_on_maximum_cart_amount', 20, 1 );
This code checks whether the cart total (excluding tax and shipping) exceeds the specified maximum amount ($500 in the example). If so, it applies an additional fee of $20 (or whatever amount you specify) to the cart. You can change the maximum amount $max_amount
and the rate 1TP4Additional_rate
According to your needs.
Adding this fee can help you cover the additional costs associated with processing large orders and can also influence customers' purchasing behavior by balancing the cost of doing business. Always remember to clearly communicate any additional fees to your customers and explain the reasons for them, to maintain transparency and trust.
Additional fee based on the quantity of items in the cart
To add additional fees to a customer's cart based on the quantity of items in the cart in WooCommerce, you can use the following code. This can be useful, for example, if you want to incentivize the purchase of larger quantities to reduce handling or printing costs, as in the example of event tickets. Another common case scenario is to handle some sort of discounting on orders of multiple items wholesaler-style. This code snippet can be inserted into the functions.php
Of your WordPress theme:
function add_tariff_base_on_quantity_cart( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
$quantity_to_avoid_tariff = 10; // Set the amount of items needed to avoid the tariff
$tariff_additive = 5; // Sets the amount of the tariff for carts below the specified quantity
$quantity_total = 0;
// Calculates the total quantity of items in the cart
foreach ( $cart->get_cart() as $cart_item ) {
$quantity_total += $cart_item['quantity'];
}
// If the total quantity is less than the specified threshold, apply the rate
if ( $quantity_total add_fee( 'Additional Printing Costs', $quantity_add_tariff );
}
}
add_action( 'woocommerce_cart_calculate_fees', 'add_base_rate_on_quantity_cart', 20, 1 );
In this code:
$quantity_to_avoid_tariff.
indicates the number of items a customer must purchase in order not to have to pay the additional fee.1TP4Additional_rate
is the amount of the fee that will be charged if the cart contains fewer items than the minimum quantity required.- The cycle
foreach
sums all the quantities of the items in the shopping cart. - If the total quantity of items in the cart is less than the defined threshold, a charge is added to the cart.
This approach allows you to incentivize purchases in larger quantities, potentially reducing operational costs associated with handling smaller orders or individual ticket printing. Remember to clearly communicate this policy to your customers to ensure transparency and maintain a good purchasing experience.
Additional fee based on customer's country of origin
To add additional rates to a customer's cart based on the customer's country in WooCommerce, you can use the following PHP code. This snippet should be placed in the functions.php
of your WordPress theme. The code allows you to charge extra fees based on the customer's shipping country, which can be useful to cover additional costs such as customs duties, export taxes or insurance required for shipping to certain countries.
function add_basic_rates_on_customer_country( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
$customer_country = WC()->customer->get_shipping_country();
$additional_rate = 0;
$ariff_name = "Additional Shipping Costs";
switch ( $country_customer ) {
case 'IT':
// No additional fees for Italy
break;
case 'US':
// For example, for US, you may want to add a tariff to cover customs fees
1TP4Additional_tariff = 5;
break;
// Add other countries and their tariffs here
default:
// You may want to add a default tariff for all other countries not specified
$tariff_additional = 10;
break;
}
if ( $ariff_add_fee > 0 ) {
$cart->add_fee( $ariff_name, $tariff_additional );
}
}
add_action( 'woocommerce_cart_calculate_fees', 'add_tariff_base_on_customer_country', 20, 1 );
This code checks the customer's shipping country and applies a specific additional fee if the country matches one of the cases in the block switch
. You can change the country codes ('IT'
, 'US'
, etc.), the rates charged, and the name of the rate ("Additional Shipping Costs"
) depending on your needs.
Remember that transparent communication of these additional fees to your customers is essential to maintaining a good shopping experience and customer trust. Be sure to clearly inform them of possible additional fees during the checkout process.
Additional fee based on user group
To add extra fees to the WooCommerce shopping cart based on the user's role, without changing product prices but simply applying an extra fee for certain roles, you can use the following PHP code. This code snippet should be placed in the file functions.php
of your WordPress theme. This approach allows you to keep the same price for all users but add additional costs for certain user roles, which can be useful in various situations, such as covering specific operational costs associated with certain user groups.
function add_basic_rates_on_user_role( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
$utente = wp_get_current_user();
$roles_user = (array) $utente->roles;
$tariff_additive = 0;
$ariff_name = "Additional Service Costs";
// Example to apply an additional rate to users with role "customer"
if ( in_array( 'customer', $rule_user ) ) {
1TP4Additional_rate = 5;
}
// Example to apply different tariff to users with role "subscriber"
elseif ( in_array( 'subscriber', $rules_user ) ) {
$tariff_additive = 3;
}
if ( $tariff_additional > 0 ) {
$cart->add_fee( $ariff_name, $tariff_additional );
}
}
add_action( 'woocommerce_cart_calculate_fees', 'add_tariff_base_on_user_role', 20, 1 );
In this code:
- The role of the currently logged on user is checked.
- Depending on the role, a specific additional fee is charged. In our example, users with the role
customer
will incur an additional fee of $5, while users with the rolesubscriber
In one of $3. - You can modify roles and rates as needed, adding or removing conditional blocks as needed.
This method allows significant flexibility in charging additional fees based on user roles, giving you a way to cover specific costs or incentivize certain purchase behaviors while keeping product pricing uniform for all users. Be sure to clearly communicate these additional fees on your website to maintain transparency with your customers.
A concrete example of using this additional fee is the "Subscribe and Save" method as is often done on stock image sales sites.
Adding extra rates without losing customers
Adding customized rates to a user's shopping cart can be an effective cost recovery and profitability boosting tool for your online business. However, it is critical to manage this strategy carefully to avoid unintended effects on customer buying behavior. Here are some tips on how to implement add-on fees effectively and consciously:
1. Clearly Communicate Additional Rates
Being transparent about additional fees from the outset can help reduce cart abandonment rates. Make sure your customers are well informed about any additional fees before they checkout. This can be accomplished through detailed product descriptions, FAQs, or during the checkout process.
2. Evaluates the Impact on the Conversion Rate
Closely monitor your cart conversion and abandonment rates after introducing the additional fees. If you notice a significant negative impact, consider revising your strategy. It may be useful to run A/B tests to evaluate the effect of different fees on purchase behavior.
3. Automate the Process
Automating the process of applying additional tariffs is crucial to maintaining operational efficiency. Using code snippets provided for specific situations, such as tariffs based on country, weight, quantity in cart, or user role, you can automate the application of these tariffs without manual intervention.
4. Offer Added Value
When possible, offset the introduction of additional fees by offering added value to your customers. This may include faster shipping, better packaging, or access to exclusive offers. Providing additional value can help justify the extra costs in the eyes of your customers.
5. Choose Context-Based Strategies
Carefully assess the context of your market and your customers' needs before deciding to charge additional fees. In some cases, such as for niche or high-demand products, customers may be less responsive to such fees. In other contexts, it may be appropriate to look for other strategies to cover operating costs.
6. Maintain a Balanced Approach
The ultimate goal should be to maintain a balance between cost recovery and providing a positive, frictionless customer experience. Periodically evaluate the effectiveness of your add-on fees and be ready to make adjustments based on customer feedback and key metrics for your site.
By implementing these tips, you can leverage additional fees as a tool to increase profitability without compromising customer satisfaction or conversion rates.