Skip to content

Instantly share code, notes, and snippets.

@mikejolley
Created October 28, 2012 19:28
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save mikejolley/3969579 to your computer and use it in GitHub Desktop.
Save mikejolley/3969579 to your computer and use it in GitHub Desktop.
WooCommerce - Create a coupon via PHP
$coupon_code = 'UNIQUECODE'; // Code
$amount = '10'; // Amount
$discount_type = 'fixed_cart'; // Type: fixed_cart, percent, fixed_product, percent_product
$coupon = array(
'post_title' => $coupon_code,
'post_content' => '',
'post_status' => 'publish',
'post_author' => 1,
'post_type' => 'shop_coupon'
);
$new_coupon_id = wp_insert_post( $coupon );
// Add meta
update_post_meta( $new_coupon_id, 'discount_type', $discount_type );
update_post_meta( $new_coupon_id, 'coupon_amount', $amount );
update_post_meta( $new_coupon_id, 'individual_use', 'no' );
update_post_meta( $new_coupon_id, 'product_ids', '' );
update_post_meta( $new_coupon_id, 'exclude_product_ids', '' );
update_post_meta( $new_coupon_id, 'usage_limit', '' );
update_post_meta( $new_coupon_id, 'expiry_date', '' );
update_post_meta( $new_coupon_id, 'apply_before_tax', 'yes' );
update_post_meta( $new_coupon_id, 'free_shipping', 'no' );
@redifmail
Copy link

How can we add something like add X quantity of any product and get Y % off?

@Stevemoretz
Copy link

Better using the wc_coupon instance with its save method now.

@CoachDom
Copy link

CoachDom commented Oct 26, 2023

@mikejolley Does this work in 2023? I'm just starting a new store with my own designs and I can't really afford to pay for those 50$ a month plugins (not before I will actually start making some money on this :D)
Thank you for all the effort you put in this so far!
Dom

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment