WordPress中EventOn+WooCommerce实现购票自动赠免费票的方法
Hey there! Let's figure out how to make that free EventOn ticket automatically pop into the cart when a user adds your target paid ticket (the one with product ID 56412). Since you want to lean on built-in plugin functionality as much as possible, we can use WooCommerce's native hooks (which EventOn integrates with, since its tickets are WooCommerce products) to get this done without extra plugins.
Step 1: Get Your Free Ticket's Product ID
First, find the product ID of your free EventOn ticket. You can grab this by editing the free ticket in WordPress—look for the number in the URL bar (e.g., post=1234 means ID is 1234). Let's call this FREE_TICKET_ID for now.
Step 2: Use WooCommerce's woocommerce_add_to_cart Hook
WooCommerce has a built-in action hook that triggers right after a product is added to the cart. We'll use this to check if the added product is your target ticket (56412), and if so, add the free ticket.
Add this code to your theme's functions.php file (or a custom plugin file for safer updates, so you don't lose changes when updating your theme):
add_action( 'woocommerce_add_to_cart', 'auto_add_free_event_ticket', 10, 6 ); function auto_add_free_event_ticket( $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data ) { // Replace 1234 with your free ticket's actual product ID $free_ticket_id = 1234; $target_ticket_id = 56412; // Check if the added product is our target paid ticket if ( $product_id == $target_ticket_id ) { $cart = WC()->cart; $free_ticket_in_cart = false; // Avoid adding duplicate free tickets by checking the cart first foreach ( $cart->get_cart() as $item ) { if ( $item['product_id'] == $free_ticket_id ) { $free_ticket_in_cart = true; break; } } // Add the free ticket if it's not already in the cart if ( ! $free_ticket_in_cart ) { $cart->add_to_cart( $free_ticket_id ); wc_add_notice( 'A free event ticket has been added to your cart!', 'notice' ); } } }
Step 3: Verify Your Free Ticket Setup
Make sure your free EventOn ticket is configured correctly in WooCommerce:
- Set its price to
0(so it's truly free for customers) - Ensure it has enough stock (or set it to unlimited stock if that makes sense for your event)
- Confirm it's set as a published, purchasable product (not hidden or in draft status)
Why This Works With "Built-in" Functionality
That evoAddToCart button you shared triggers WooCommerce's native add-to-cart process under the hood. The woocommerce_add_to_cart hook is a core feature of WooCommerce—no third-party plugins needed, just leveraging the extension points both WooCommerce and EventOn are designed to support for customizations like this.
If you ever need to adjust which paid ticket triggers the free add, just swap out the $target_ticket_id value in the code.
内容的提问来源于stack exchange,提问作者Navruz Madibragimov

