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');
}
...
}
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Note: OP and me resolved the question/issue via chat — and despite the actual problem source is not known for sure, in the actual AJAX callback used by OP, there was actually no (or maybe OP had forgotten to make the) do_action() call. 🙂
Original Revised Answer (for reference):
If you have something like so in your actual code, i.e. the actions are registered properly:
add_action( 'wp_ajax_<your action>', 'my_ajax_callback' ); // for logged-in users
add_action( 'wp_ajax_nopriv_<your action>', 'my_ajax_callback' ); // for all other users
add_action( 'prefix_item_added_to_cart', 'send_email_to_user' );
Then I don’t see why would the callback function is not getting called — unless of course, if the conditional (if ( $cart_id )) returns false.
But what’s that $args in your add_action() call? That parameter should be an integer, which is the callback priority.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0