5

I have previously asked this question however it does not answer the question of how to retrieve data from a coupon in WooCommerce. Both questions involve coupons, however, the first question is asking how does one set the metadata and this question asks how you retrieve the data.


I am trying to get the details of a coupon from WooCommerce by the coupon code. However, I am not sure on how I should try to go about doing this.

I have tried the code below. However, it gives me the error Call to undefined function WC_Coupon()

$coupon_code = 'save10percent';
global $woocommerce;
$c = WC_Coupon($coupon_code);

How should one go about getting the details of a coupon?

Marcello B.
  • 3,822
  • 10
  • 45
  • 61
  • You got **this answer** already is one of **your question answer**: [Set a coupon description in WooCommerce](https://stackoverflow.com/questions/47360869/set-a-coupon-description-in-woocommerce/47361312#47361312) … – LoicTheAztec Nov 27 '17 at 18:09
  • 2
    @LoicTheAztec that question is not the same as this post title and question and therefore is not duplicate! – Hamid Araghi Sep 09 '19 at 16:45
  • 1
    @HamidAraghi Sorry but the way to get the data is the same, using `WC_Coupon` **getter** methods instead of **setter** methods that this OP asked before… So in both cases you use `WC_Coupon` class methods on the `WC_Coupon` instance object. In My linked answer, I have showed how to get the `WC_Coupon` object and I have added the link to `WC_Coupon` Class available methods… This has also been answered in other threads on how to get coupon data (from orders for example, which is the same process, using `WC_Coupon` getter methods on the `WC_Coupon` Object). – LoicTheAztec Sep 12 '19 at 18:19

1 Answers1

17

I figured it out. In order for the WC_Coupon function to work, I needed to add the "new" keyword prior to calling the function. As demonstrated below.

$coupon_code = 'save10percent';
global $woocommerce;
$c = new WC_Coupon($coupon_code);

Now I can get details about the coupon like so

echo "Discount Amount ".$c->amount."<br>";//Get Discount amount
echo "Discount Type ".$c->discount_type."<br>";//Get type of discount
echo "Individual Use ".$c->individual_use."<br>";//Get individual use status
echo "Usage Count ".$c->usage_count."<br>";//Get number of times the coupon has been used
echo "Uage Limit ".$c->usage_limit."<br>";//Get usage limit
echo "Coupon Description ".$c->description."<br>";//Get coupon description
Marcello B.
  • 3,822
  • 10
  • 45
  • 61
  • 4
    Depending of your context, you cannot access the object directly. Instead, you need to use woocommerce helpers eg: $c->get_amount() – Jeff Monteiro Jul 28 '20 at 17:52