Menu Close

Apply coupon programmatically in Woocommerce cart

Codeamend

In Woocommerce we can use apply coupon functionality to improve sales in two ways,

  1. Customers can manually enter a coupon code and refresh the Cart and see their discount apply
  2. You can do that automatically (or “programmatically” as we say in the dark web) by enabling coupons when a user adds a product to the WooCommerce Cart.

All you’ve got to do is create a coupon, and then a PHP function will do the whole work. Automation is the best option to get more sales in ecommerce!

Move Coupon Form Under “Proceed to Checkout” on WooCommerce Cart Page
add_action( 'woocommerce_before_cart', codeamend_apply_coupon);
  
function codeamend_apply_coupon() {
    $coupon_code = 'freecoupon';
    if ( WC()->cart->has_discount( $coupon_code ) ) return;
    WC()->cart->apply_coupon( $coupon_code );
    wc_print_notices();
}
 

Apply a Coupon Programmatically for specific product is added in the Cart

add_action( 'woocommerce_before_cart', 'codeamend_apply_matched_coupons' );
function 'codeamend_apply_matched_coupons' () {
    $coupon_code = 'freecoupon';
    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( 456);
    if ( in_array( $cart_item['product_id'], $autocoupon ) ) {  
        WC()->cart->apply_coupon( $coupon_code );
        wc_print_notices();
    }
    }
}
 

Note:

  • 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 “freecoupon”, which is the coupon code we will use later in the PHP snippet).
  • 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 = “456”)
Posted in WooCommerce

You can also read...