Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if coupon is applied in woo commerce

I need to find a way to check if a coupon is applied to Woocommerce checkout, if so I would like to do something. I have tried searching around for this and cannot find a solution.

here is a slimmed down version of what I am trying:

add_action('woocommerce_before_cart_table', 'apply_product_on_coupon');
function apply_product_on_coupon( ) {
    global $woocommerce;
    $coupon_id = '12345';

        if( $woocommerce->cart->applied_coupons === $coupon_id ) {
        echo 'YAY it works';
    }
}

So is this not the right way to check if the coupon exists in cart? if( $woocommerce->cart->applied_coupons === $coupon_id )

like image 472
Derek Avatar asked Nov 20 '13 15:11

Derek


4 Answers

From your example, something like this might work. This is untested, but should give you a step in the right direction:

add_action('woocommerce_applied_coupon', 'apply_product_on_coupon');
function apply_product_on_coupon( ) {
    global $woocommerce;
    $coupon_id = '12345';
    $free_product_id = 54321;

    if(in_array($coupon_id, $woocommerce->cart->get_applied_coupons())){
        $woocommerce->cart->add_to_cart($free_product_id, 1);
    }
}
like image 162
maiorano84 Avatar answered Nov 11 '22 00:11

maiorano84


global $woocommerce;
if (!empty($woocommerce->cart->applied_coupons))
{
        //print_r($woocommerce->cart->applied_coupons); - keys of coupons here
}
like image 43
realmag777 Avatar answered Nov 11 '22 02:11

realmag777


This might be an ages issue but an easy solution is to use

WC()->cart->applied_coupons

This return array lists of applied coupons, you can then use foreach, for or in_array to check applied coupons.

Hope that helps

like image 2
Ryan S Avatar answered Nov 11 '22 02:11

Ryan S


If you know the coupon code but not the coupon post ID, you can use this mash up of realmag777's answer and maiorano84's answer.

function CheckCouponIsApplied($cpn_code)
{
    global $woocommerce;
    $lowercasecouponcode = strtolower($cpn_code); //ENSURE LOWERCASE TO MATCH WOOCOMMERCE NORMALIZATION
    return in_array($lowercasecouponcode, $woocommerce->cart->applied_coupons);
}
like image 2
Marcello B. Avatar answered Nov 11 '22 02:11

Marcello B.