Users can manually enter a coupon code, refresh the Cart and see their discount apply… or you can do that automatically (or “programmatically” as we say in the dark web) when a user adds a product to the WooCommerce Cart 🙂

All you’ve got to do is creating a coupon, and then a PHP function will do the whole work. Automation is the best thing in the world!

WooCommerce: how to add a coupon programmatically if a product is added to cartWooCommerce: how to add a coupon programmatically if a product is added to cart
WooCommerce: how to add a coupon programmatically if a product is added to cart

PHP Snippet 1: Apply a Coupon Programmatically if a Product is in the Cart

Notes:

  1. Create a coupon code that you want to apply once a certain product is added to cart (go to WooCommerce / Coupons / Add New and decide your coupon code. For example “freeweek”, which is the coupon code we will use later in the PHP snippet)
  2. Identify your product ID (go to WordPress / Products and hover onto the product you want to use the coupon with. Whatever ID shows in the URL bar, take a note. In our example, we will target product ID = “745”)
/**
 * @snippet       Apply a Coupon Programmatically if Product @ Cart - WooCommerce 
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @compatible    WC 4.1
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */
 
add_action( 'woocommerce_before_cart', 'bbloomer_apply_matched_coupons' );
 
function bbloomer_apply_matched_coupons() {
 
    $coupon_code = 'freeweek'; 
 
    if ( WC()->cart->has_discount( $coupon_code ) ) return;
 
    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
 
    // this is your product ID
    $autocoupon = array( 745 );
 
    if ( in_array( $cart_item['product_id'], $autocoupon ) ) {   
        WC()->cart->apply_coupon( $coupon_code );
        wc_print_notices();
    }
 
    }
 
}

PHP Snippet 2: Apply a Coupon Programmatically for ALL Products

/**
 * @snippet       How to Apply a Coupon Programmatically - WooCommerce Cart
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @compatible    WC 4.1
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */
 
add_action( 'woocommerce_before_cart', 'bbloomer_apply_coupon' );
 
function bbloomer_apply_coupon() {
    $coupon_code = 'freeweek'; 
    if ( WC()->cart->has_discount( $coupon_code ) ) return;
    WC()->cart->apply_coupon( $coupon_code );
    wc_print_notices();
}
Share:

Leave a Reply