Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[General Snippets] Create a coupon programatically
/**
* Create a coupon programatically
*/
$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' );
@pdchaudhary

This comment has been minimized.

Copy link

pdchaudhary commented Apr 27, 2019

for expiry_date use this
//$date should be in timestamp
update_post_meta( $new_coupon_id, 'date_expires',$date );

@roeeyossef

This comment has been minimized.

Copy link

roeeyossef commented Dec 11, 2019

It doesn't really work. it create 4 coupons instead of 1 when added to functions.php - how come?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.