Auto Apply Coupon When The Product Match With ID XX

To automatically apply a coupon code when a product with the ID of XX is added to the cart, you would need to implement this logic in your application or website’s code. Here’s a general outline of how you could achieve this:

There are two main things to change, the product ID, and the coupon code.

Step 1: Go to “WooCommerce” > “Coupons”. This is where you can manage and create coupons for your store.

Step 2: To apply automatically apply a coupon code when a product with the ID of XX is added to the cart, you can use the following code snippet. This code should be added to your theme’s functions.php file or in a custom plugin.

/**
 * Snippet Name:    To apply automatically apply a coupon code when a product with the ID of XX
 * Snippet Author:  https://wpproblog.com
 */

//To apply automatically apply a coupon code when a product with the ID of XX
add_action( 'woocommerce_before_calculate_totals', 'apply_coupon_wpproblog' );
function apply_coupon_wpproblog( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // HERE define your coupon code
    $coupon_code = 'NEW50CODE';

    // HERE define the product ID
    $product_id = 17109;

    // Loop through cart items
    foreach ( $cart->get_cart() as $cart_item ) {
        if( $cart_item['product_id'] == $product_id ) {
            $cart->add_discount( $coupon_code );
            break; // Stop the loop
        }
    }
}

Make sure to replace 'NEW50CODE' with your actual coupon code and $product_id with the desired product ID. Additionally, consider adjusting the code based on your specific requirements and testing it thoroughly to ensure it works as expected.