![](https://secure.gravatar.com/avatar/d201a07d5d3584f26dd49c22f6816f8b?s=80&d=retro&r=g) marianne
|
February 14, 2025 at 9:53 pm
We’ve decided to implement a feature that lets users add multiple events from the same page (e.g., an event category page) with a single button click. To achieve this, we developed a custom shortcode to list all the events under a certain category and use JavaScript to pass ticket IDs via an AJAX call.
Everything works well until… despite the add_ticket_to_cart function returning true, the tickets are not actually added to the cart for some reason.
Below, I’ve provided my code for the AJAX handler.
// Check if the nonce is valid
if ( ! wp_verify_nonce( $_POST[‘nonce’], ‘events_list_add_to_cart’ ) ) {
wp_send_json_error( ‘Invalid nonce’ );
}
// Sanitize the tickets array.
$tickets = array_map( ‘absint’, $_POST[‘tickets’] );
$loader = LoaderFactory::getLoader();
$cart = \EE_Registry::instance()->load_core( ‘Cart’ );
$tracker = $loader->getShared( ‘EventEspresso\modules\ticket_selector\TicketDatetimeAvailabilityTracker’ );
$ticket_objects = \EEM_Ticket::instance()->get_tickets_with_IDs( $tickets );
// Get the ticket objects.
foreach ( $ticket_objects as $key => $ticket ) {
// get the number of spaces left for this datetime ticket
$available_spaces = $tracker->ticketDatetimeAvailability( $ticket );
// compare available spaces against the number of tickets being purchased
if ( $available_spaces >= 1 ) {
// add event to cart
if ( $cart->add_ticket_to_cart( $ticket, 1 ) ) {
$tracker->recalculateTicketDatetimeAvailability( $ticket, 1 );
}
}
}
wp_send_json_success( ‘Tickets added to cart’ );
|