|$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' );|
You would put this code inside a new function in your functions.php file. It's up to you when you'd need call that function. E.g., I am using it so that when a certain page loads, the function is called to create the coupon and then email the code to the user. If you wanted to show the new code on screen, you could quite easily have the function return 'UNIQUECODE'.
NB - Normally, you'd create a coupon by logging in to yoursite.com/wp-admin and going WooCommerce > Coupons > Add Coupon.
I have done this with some changes. Here's my code on functions.php (then I created a private page where i call this function and it generates the coupon automatically.)
/* generate $15 off coupons */
Would it be possible to use this code to automatically create a coupon code at checkout using the customer's "username" as the coupon code? I want it to be easy to remember for the customers so they can share the coupon codes......I have an affiliate program based on their coupon codes.
Ex. I create username "Mac" at checkout(username required on my site) and instantly coupon code "Mac" would be generated. This coupon could be used unlimited times and would be for 20% Off. If user name "Tim" is used, "Tim" would become a 20% Off coupon code etc.
Any help would be greatly appreciated, thanks in advance!
I want to generate woocommerce coupon code dynamically.
My requirements is that after complete the order automatically generate one coupon code in admin side woocommerce coupon code list for particular product.
So any one know my above requirement solutions then please help me.
for some reason i am getting that wp_insert_post is undefined after i added some code to this function,
This is my code and I am trying to add a coupon for my online store but it's not working
add_action( 'woocommerce_before_cart', 'sh_coupons_matched' );
I have followed this WooCommerce coupon code tutorial to implement the whole process
@dcx15 yikes it's 8 years old but it should work. However, I'd suggest looking into using the