Create a coupon programatically in WooCommerce

We will need to add this code to our child theme’s functions.php file or via a plugin that allows custom functions to be added. We always have to remember, we don’t have to add custom code directly to our parent theme’s functions.php file as this will be wiped entirely when we update the theme.

/**
 * Create a coupon programatically
 */
$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' );

13 comments:

  1. Thanks for the information it is really helpful
    https://list.ly/list/4yln-leading-seo-company-in-coimbatore-proplus-logics

    ReplyDelete
  2. This is my first visit to your web journal! We are a group of volunteers and new activities in the same specialty. Website gave us helpful data to work. cupom de desconto sunset cosméticos

    ReplyDelete
  3. Your information is helpful. Do check out these coding cheat sheets for more such coding shortuts. Thanks.

    ReplyDelete