0

I have to trigger an ajax call based on a custom field changes on checkout form which is to add a discount. But if I call the hook to add discount into subtotal of the cart it does not do anything. Note that ajax call is working fine. Even if I use woocommerce_cart_calculate_fees hook outside of ajax callback function it worked.

add_action('wp_ajax_test', 'test');
add_action('wp_ajax_nopriv_test', 'test');

function test(){
  add_action('woocommerce_cart_calculate_fees' , 'add_custom_fees');
}


function add_custom_fees( WC_Cart $cart ){

    // Calculate the amount to reduce
    $discount = $cart->subtotal * 0.2;
    $cart->add_fee( 'You have more than 3 items in your cart, a 10% discount has been added.', -$discount);
}

1 Answer 1

0

The problem you are having is that the add_action function will only affect the current request, which in this case is your Ajax call. Afterwards, when you submit the form, that is a different request, the action is no longer present.

To achieve what you want, you have to have some way of modifying the form so that the discount will be noted when it is submitted.

You would use Ajax, perhaps, to check if a discount is allowed, and return the text for the user and/or the proper item to add to the form to make it have the discount later.

Here is roughly what I mean:

add_action('wp_ajax_discount', 'maybe_discount');
function maybe_discount() { 
    /* determine if discount is appropriate, then */
    if ($discount) {
        echo json_encode('status'=>'discount', 'text'=>'....');
    } else {
        echo json_encode('status'=>'nodiscount');
    die();
}

/* On the client side, you will use the returned information to
 * show something to the user, or possibly alter the form itself
 * (I don't know what WooCommerce supports).
 * Then when you *submit* the form, you might need a hook like this:
 */

add_action('some_woocomerce_hook_here','add_my_discount');
function add_my_discount( WC_Cart $cart ) {
    $discount = $cart->subtotal * 0.2;
    $cart->add_fee( 'You have a discount...', -$discount);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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