woocommerce add coupon programmatically code example

Example 1: woocommerce create coupon programmatically

/**
* 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' );

Example 2: woocommerce apply coupon with add to cart

function wc_ninja_apply_coupon( $coupon_code ) {
	if ( 'test_code' === $coupon_code ) {
		$product_id = 99;
		WC()->cart->add_to_cart( $product_id );
	}
}
add_action( 'woocommerce_applied_coupon', 'wc_ninja_apply_coupon' );

Tags:

Misc Example