Add a fee to WooCommerce Total Cart based on an URL query variable

33 Views Asked by At

In the following code, I add a percentage fee to WooCommerce Total Cart, but the condition in the IF statement, doesn't work. I somehow checked everything.

// Adding Nutritionist Fees
add_action('woocommerce_cart_calculate_fees', 'custom_nutritionist_fee');

function custom_nutritionist_fee() {
    $chec = (isset($_GET['diet']) && esc_attr( $_GET['diet'] ) == 'Nutritionist') ? 1 : 0;
    print($chec);

    if (isset($_GET['diet']) && esc_attr( $_GET['diet'] ) == 'Nutritionist') {
     $percentage = 0.25;
    $percentage_fee = (WC()->cart->get_cart_contents_total() + WC()->cart->get_shipping_total()) * $percentage;
    // Add the fee to the cart
    WC()->cart->add_fee(__('Nutritionist Fees', 'txtdomain'), $percentage_fee);
    }
//  return;
}

But the IF statement stays false all the time.

1

There are 1 best solutions below

0
LoicTheAztec On

You need to add first the query string value (logic) in a WC Session variable. Then you can use the WC Session variable to enable/disable your custom "Nutritionist" Fee.

Try the following:

add_action('template_redirect', 'set_diet_query_string_value_to_wc_session');
function set_diet_query_string_value_to_wc_session() {
    if ( isset($_GET['diet']) && ! empty($_GET['diet']) ) {
        WC()->session->set('nutritionist_fee', strval($_GET['diet']) === 'Nutritionist' ? true : false);
    }
}

// Adding Nutritionist Fees
add_action('woocommerce_cart_calculate_fees', 'custom_nutritionist_fee');
function custom_nutritionist_fee( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( WC()->session->get('nutritionist_fee') ) {
        $fee_rate   = 0.25;
        $fee_amount = ($cart->get_cart_contents_total() + $cart->get_shipping_total()) * $fee_rate;
        // Add the fee to the cart
        $cart->add_fee(__('Nutritionist Fees', 'txtdomain'), $fee_amount);
    }
}

Code goes in functions.php file of your child theme (or in a plugin). Tested and works.