How to programmatically create a Woocommerce coupon

0
265

Today i had to create a system that would create different coupons for a site in Woocommerce.

The idea is very simple:

  1. Check if there is a valid Coupon
  2. If is not there create the coupon
//function to check if a coupon is valid
function check_if_coupon_valid( $couponcode ) {
        $coupon = new WC_Coupon( $couponcode );
        $discounts = new WC_Discounts( WC()->cart );
        $valid_response = $discounts->is_coupon_valid( $coupon );
        if ( is_wp_error( $valid_response ) ) {
            return false;
        } else {
            return true;
        }
    }
    $couponcode = "any coupon code";
    $couponamount = "any value"
    if(!check_if_coupon_valid($couponcode)){
        $discount_type = 'fixed_cart'; // Type: fixed_cart, percent, fixed_product, percent_product

        $coupon = array(
            'post_title' => $couponcode,
            'post_content' => '',
            'post_status' => 'publish',
            'post_author' => 1,
            'post_type'		=> 'shop_coupon'
        );

        $newcouponid = wp_insert_post( $coupon );

// Add meta -- here depending on the data we wish to change we can make different changes
//this code adds a coupon with a fixed amount that is offered with no limit to the product and individual use
       update_post_meta( $newcouponid, 'product_ids', '' );
        update_post_meta( $newcouponid, 'exclude_product_ids', '' );
        update_post_meta( $newcouponid, 'discount_type', $discount_type );
        update_post_meta( $newcouponid, 'free_shipping', 'no' );
        update_post_meta( $newcouponid, 'coupon_amount', $couponamount );
        update_post_meta( $newcouponid, 'individual_use', 'no' );
        update_post_meta( $newcouponid, 'expiry_date', '' ); 
        update_post_meta( $newcouponid, 'usage_limit', '' );
       
        update_post_meta( $newcouponid, 'apply_before_tax', 'yes' );

    }

If you have any questions please add a comment and i will try to answer as fast as i can

LEAVE A REPLY

Please enter your comment!
Please enter your name here