Website Building » WooCommerce » How Do I Create a Coupon Code in WooCommerce Programmatically?

How Do I Create a Coupon Code in WooCommerce Programmatically?

Last updated on January 11, 2023 @ 11:56 am

Adding a coupon code to WooCommerce is a great way to offer discounts to your customers. There are two ways to do this: through the WordPress admin panel or by adding code to your functions.php file.

To add a coupon code through the WordPress admin panel, log into your site and go to WooCommerce > Coupons. From there, click on the Add Coupon button and enter your coupon details. Make sure to select the Enable this coupon checkbox before saving.

If you want to add a coupon code programmatically, you can use the following code:

PRO TIP: If you are not a developer or comfortable with code, do not attempt to follow the instructions in this article. You could break your WooCommerce installation.
$coupon = array(
    'post_title' => $code, // dynamic coupon code
    'post_content' => '',
    'post_status' => 'publish',
    'post_author' => 1,
    'post_type' => 'shop_coupon'
);
$new_coupon_id = wp_insert_post( $coupon );

// Set meta data for new coupon post
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' );

This code creates a new coupon post with the title of the coupon being set to the variable $code, sets some properties on the coupon post like post_status, post_author and post_type then it uses the wp_insert_post() function to insert the coupon post into the database. then it updates the metadata of the post just created by the function update_post_meta() with different values, like discount_type, coupon_amount, individual_use, product_ids,exclude_product_ids, usage_limit, expiry_date,apply_before_tax,free_shipping.

It is important to note that the wp_insert_post() and update_post_meta() functions are core WordPress functions and will only work if the website is running on WordPress.

Madison Geldart

Madison Geldart

Cloud infrastructure engineer and tech mess solver.