Woocommerce

Create a coupon programatically in wordpress

This code creates a new coupon with a unique code, a specific amount, and discount type.

The $coupon_code variable sets the code for the coupon, and $amount sets the amount of the discount. The $discount_type variable determines the type of the discount, which can be one of the following: fixed_cart, percent, fixed_product, percent_product.

The wp_insert_post() function creates a new post with a post type of shop_coupon. The coupon information is then saved as post meta using the update_post_meta() function. This includes the discount type, coupon amount, individual use, product IDs, usage limit, expiry date, whether the coupon should be applied before or after taxes, and whether it provides free shipping.

If you want to create a coupon with different details, you can edit the values of the variables and the post meta being updated. For example, you can set an expiry date for the coupon or limit it to specific products.

    
$coupon_code = 'UNIQUECODE'; // Code $amount = '10'; // Coupon Amount $discount_type = 'fixed_cart'; // choose 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' );

Leave a Reply

Your email address will not be published. Required fields are marked *