custom add coupon woocommerce code example
Example 1: woocommerce create coupon programmatically
$coupon_code = 'UNIQUECODE';
$amount = '10';
$discount_type = 'fixed_cart';
$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 );
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' );