3

ORIGINAL QUESTION:

We need to know if a coupon has specifically granted free shipping.

In my test scenario I have two coupons applied to the cart, one with free shipping and one without. The var_dump clearly shows one coupon like this:

 ["free_shipping"]=>
   bool(true)

However, when using

  echo "<p>Free shipping: ".(int)$coupon->free_shipping."</p>";

It always displays 0.

I can't figure out what I am doing wrong.

Here's the code:

 add_action('woocommerce_before_cart_totals', 'check_free_shipping_on_coupon');

function check_free_shipping_on_coupon() {

    global $woocommerce;

    if ( ! empty( $woocommerce->cart->applied_coupons ) ) {


        $my_coupon = $woocommerce->cart->get_coupons() ;


        foreach($my_coupon as $coupon){

            if ( $post = get_post( $coupon->id ) ) {

                        echo "<p>ID: ".$coupon->id . "</p>";

                        echo "<p>Code: ".$coupon->code."</p>";

                        echo "<p>Amount: ".$coupon->amount."</p>";

                        if ( !empty( $post->post_excerpt ) ) {

                        echo "<p>Excerpt: ".$post->post_excerpt."</p>";

                        }

                        echo "<p>Free shipping: ".(int)$coupon->free_shipping."</p>";

                        if ( (int)$coupon->free_shipping == '1'){//I want to do stuff here;

                        }

                        //Dump everything for reference
                        echo '<pre>' , var_dump($coupon) , '</pre>';


            }
        }
    }
}

UPDATE:

I found another question here: Set all shipping methods cost to zero for a Free shipping coupon in Woocommerce that had a code snippet that solved my question, but in a very different way. I am still curious why my original code did not work.

Working code:

//Check if a coupon has granted free shipping

add_action('woocommerce_before_cart_totals', 'rnr_check_free_shipping_on_coupon');

function rnr_check_free_shipping_on_coupon() {

$applied_coupons = WC()->cart->get_applied_coupons();

    foreach( $applied_coupons as $coupon_code ){

    $coupon = new WC_Coupon($coupon_code);

    if($coupon->get_free_shipping()){

        echo 'You have a free shipping coupon!';

    }

  }

}
AJD
  • 371
  • 4
  • 14

0 Answers0