Search code examples
phpwordpresscookieswoocommercecart

Add fee to WooCommerce cart using a cookie


I have a scenario in which there's a number determined early in the user flow. I'm saving that as a cookie using setcookie( "mileage", $distance_surcharge, time() + 36000 );.

I'm then trying to use the value from that cookie to add a surcharge to my cart, but it seems as though the value from the cookie is not being passed through.

Here's the snippet from my functions.php file as instructed by Woocommerce docs: https://docs.woocommerce.com/document/add-a-surcharge-to-cart-and-checkout-uses-fees-api/

add_action( 'woocommerce_cart_calculate_fees','gt21_add_mileage' ); 
function gt21_add_mileage() { 
    global $woocommerce; 

    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) 
    return;

    if(isset($_COOKIE['mileage'])) {
        $fee = $_COOKIE['mileage'];
        $woocommerce->cart->add_fee( 'Extra Mileage Fee', $fee, true, 'standard' );
    }  
}

I can see the extra line item in the cart, but the value only gets passed through if I set $fee to an actual integer.


Solution

  • The issue seems to be more with the creation of the cookie

    This will display on the cart page the output of the cookie (for debugging purposes), as well as the addition of the fee

    // Set cookie
    function action_init() {
        // Settings
        $path = parse_url( get_option('siteurl'), PHP_URL_PATH );
        $host = parse_url( get_option('siteurl'), PHP_URL_HOST );
        $expiry = time() + 36000;
      
        // Value
        $distance_surcharge = 10;
      
        // Set cookie
        setcookie( 'mileage', $distance_surcharge, $expiry, $path, $host );
    }
    add_action( 'init', 'action_init' );
    
    // Cart page (before cart - DEBUG)
    function action_woocommerce_before_cart() {
        // Isset
        if ( isset( $_COOKIE['mileage'] ) ) {
            $cookie = $_COOKIE['mileage'];
            
            // Output
            echo 'OK = ' . $cookie;
        } else {
            // Output
            echo 'NOT OK';
        }
    }
    add_action( 'woocommerce_before_cart', 'action_woocommerce_before_cart', 15 );
    
    // Add fee
    function action_woocommerce_cart_calculate_fees( $cart ) {
        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return;
        
        // Isset
        if ( isset( $_COOKIE['mileage'] ) ) {
            // Fee
            $fee = $_COOKIE['mileage'];
    
            // Applying fee
            $cart->add_fee( __( 'Extra Mileage Fee', 'woocommerce' ), $fee, true );     
        }
    }
    add_action( 'woocommerce_cart_calculate_fees', 'action_woocommerce_cart_calculate_fees', 10, 1 );
    

    Code goes in functions.php file of the active child theme (or active theme). Tested and works in Wordpress 5.8.1 & WooCommerce 5.8.0