Wordpress how to use add_action inside plugin function

admin

Administrator
Staff member
I need to perform / call
Code:
woocommerce_cart_calculate_fees
action inside AJAX response function as below,

Requirement is to add a discount in a certain condition to the cart.

Code:
add_action( 'wp_ajax_tcf_et_add_estimate_to_cart', 'my_function' );
my_function()
{

    // ADD SOME PRODUCTS TO THE CART
    if( certain condition  )
    {
        add_action( 'woocommerce_cart_calculate_fees', 'add_discount', 1, 1 );
        function add_discount( $cart )
        {
             global $woocommerce;
             $cart->add_fee( 'Discount' , -100 );
             return $cart;
         }
    }
    // some code    
}

I know this is completely wrong but seeking a way to do this in wordpress way? like write the
Code:
woocommerce_cart_calculate_fees
outside of
Code:
my_function
and call it if needed.

Is there any trick or technique to perform this or else is it not possible to do in Wordpress?