WordPress: do_action won't work in ajax callback function

631 Views Asked by At

I want to perform some actions when ajax tasks done successfully. For instance, if the item added to the cart, I want to send an email. Also may perform a few more actions.

Setting up do_action('prefix_item_added_to_cart', $args); doesn't recognized and so add_action doesn't perform a task, in my case sending email.

If I write code procedural code to send an email, that works fine but using do_action.

Does not work

// ajax callback function
function my_ajax_callback() {

    ...
    // add item to cart
    $cart =. new Cart();
    $cart_id = $cart->add_item($params);

    // if item added successfully
    if($cart_id){
        // perform action
        do_action('prefix_item_added_to_cart', $args);
    }
    ...

}

// action callback
function send_email_to_user($args) {

    // send email notification
    wp_mail('set params for email');

}

// action
add_action('prefix_item_added_to_cart', 'send_email_to_user', $args);

Works

function my_ajax_callback() {

    ...
    // add item to cart
    $cart =. new Cart();
    $cart_id = $cart->add_item($params);

    // if item added successfully
    if($cart_id){
        // send email notification
        wp_mail('set params for email');
    }
    ...

}
1

There are 1 best solutions below

0
On

You just need to call the function. Wherever you're getting your $args from, just pass as param of your function.

// ajax callback function
function my_ajax_callback() {

    ...
    // add item to cart
    $cart =. new Cart();
    $cart_id = $cart->add_item($params);

    // if item added successfully
    if($cart_id){
        // perform action
        send_email_to_user($args);
    }
    ...
    exit(); /// if it's ajax function, don't forget to exit or die.
}