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' );
Example 3: coupon code in link woocommerce
add_action('wp_loaded', 'add_coupon_code_to_cart_session');
function add_coupon_code_to_cart_session() {
if( empty( $_GET["code"] ) || WC()->session->get( 'custom_discount' ) ) return;
if( ! WC()->session->get( 'custom_discount' ) ) {
$coupon_code = esc_attr($_GET["code"]);
WC()->session->set( 'custom_discount', $coupon_code );
if( ! WC()->cart->is_empty() ){
WC()->cart->add_discount( $coupon_code );
}
}
}
add_action('woocommerce_add_to_cart', 'add_coupon_code_to_cart', 10, 6 );
function add_coupon_code_to_cart( $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data ){
$coupon_code = WC()->session->get( 'custom_discount' );
$applied_coupons = WC()->session->get('applied_coupons');
if( empty($coupon_code) || in_array( $coupon_code, $applied_coupons ) ) return;
WC()->cart->add_discount( $coupon_code );
}
add_action('woocommerce_cart_item_removed', 'check_coupon_code_cart_items_removed', 10, 6 );
function check_coupon_code_cart_items_removed( $cart_item_key, $cart ){
$coupon_code = WC()->session->get( 'custom_discount' );
if( $cart->has_discount( $coupon_code ) && $cart->is_empty() );
$cart->remove_coupon( $coupon_code );
}