I trying to pass a variable in woocommerce_cart_calculate_fees hook, but this code doesn't work. When I try to pass static value within a variable that's work.

$final_discount; // storing ajax value$static_value=5; // static valueif ($final_discount) {/*** custom discount for the cart in woocommerce*/// Hook before calculate feesadd_action('woocommerce_cart_calculate_fees', 'add_custom_fees');/*** Add custom fee if more than three article* @param WC_Cart $cart*/function add_custom_fees(WC_Cart $cart) {// Calculate the amount to reduceglobal $final_discount;$discount=$cart->subtotal * $final_discount / 100;$cart->add_fee('10% discount has been added.', -$discount);}}
share|improve this question

    The best way to get that working is to set your $final_discount variable using WC_Sessions in another function before, this way:

    WC()->session->set( 'final_discount', $final_discount );

    Now you can get this value anywhere on front end hooks or code using:

    $final_discount=WC()->session->get( 'final_discount' );

    So your final discount (negative fee) code will be something like:

    add_action('woocommerce_cart_calculate_fees', 'add_custom_fee', 20, 1 );function add_custom_fee( $cart ){if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;// Get the data from WC_Sessions$percent=WC()->session->get( 'final_discount' );if( $percent > 0 ){$discount=$cart->subtotal * $percent / 100;$cart->add_fee( __('Discount', 'woocommerce' ) . " ($percent%)" . $percent, -$discount);}}

    Code goes in function.php file of your active child theme (active theme).

    Tested and works.

    share|improve this answer
    • thanks. :) your code is working fine, but a little bit problem. Discounted value does not update before page refreshing, show discounted value after page refreshing. Will be session unset? How and where?– rafiq islamFeb 14 at 16:59
    • @rafiqislam It depends on when and where you are setting the value (as this is not explained in your question)… you shloud better contact me on skype chat, my ID is marsloic …– LoicTheAztecFeb 14 at 17:34

    Your Answer

     
    discard

    By posting your answer, you agree to the privacy policy and terms of service.

    Not the answer you're looking for? Browse other questions tagged or ask your own question.