php - Apply a fee via Url variable (GET) in WooCommerce
Get the solution ↓↓↓
I'm trying to carry an "add_fee" value over to review order page but it's not working.
I need to enable my check out page to wait for the url parameter "getfee".
If the getfee equals 2, then add the fee.
If it doesn't, then don't add anything.
Here's my code:
add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_surcharge' );
function woocommerce_custom_surcharge() {
global $woocommerce;
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$fee = $_GET["getfee"];
if( $fee == "2") {
$percentage = 0.01;
$surcharge = ( $woocommerce->cart->cart_contents_total + $woocommerce->cart->shipping_total ) * $percentage;
$woocommerce->cart->add_fee( 'Surcharge', $surcharge, true, '' );
}
}
So far, it adds the fee in the checkout page but when it comes to reviewing the order, it doesn't appear.
I think it could be because the checkout page doesn't have that parameter but not sure.
Any help would be greatly appreciated.
Answer
Solution:
You need to set your Url fee in a WC Session variable to avoid this problem:
// Get URL variable and set it to a WC Session variable
add_action( 'template_redirect', 'getfee_to_wc_session' );
function getfee_to_wc_session() {
if ( isset($_GET['getfee']) ) {
WC()->session->set('getfee', esc_attr($_GET['getfee']));
}
}
// Add a percentage fee
add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_surcharge' );
function woocommerce_custom_surcharge( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$fee = WC()->session->get('getfee'); // Get WC session variable value
if( $fee == "2") {
$percentage = 0.01;
$surcharge = ( $cart->cart_contents_total + $cart->shipping_total ) * $percentage;
$cart->add_fee( 'Surcharge', $surcharge, true, '' );
}
}
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: an exception occurred in the driver: could not find driver
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

