Support

Home Forums Event Espresso Premium Need help on add_ticket_to_cart function within the EE_Cart class

Need help on add_ticket_to_cart function within the EE_Cart class

Posted: February 14, 2025 at 9:53 pm

Viewing 2 reply threads


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’ );


marianne

February 16, 2025 at 8:33 pm

It seems this only does not work in Ajax callback. I have tried to put the same code into ‘init’ hook, and the ticket does added to the cart upon page refresh. Not sure why this is happening. Is there a way to make this work?


marianne

February 16, 2025 at 9:17 pm

Resolved by retrieving the same session in the ajax hanlder.

Viewing 2 reply threads

The support post ‘Need help on add_ticket_to_cart function within the EE_Cart class’ is closed to new replies.

Have a question about this support post? Create a new support post in our support forums and include a link to this existing support post so we can help you.

Event Espresso