WP CLI Script to Duplicate WooCommerce Coupons

I love writing WP CLI scripts to accomplish tasks in WooCommerce. Recently we needed to generate hundreds of coupons that had a standard prefix + a unique code. We also needed to update the coupon meta for _wc_url_coupons_unique_url to use the unique code since our coupons apply via links.

There were a few no-code solutions I found that could have worked, but they all involved exporting data into a spreadsheet, updating the spreadsheet, and then using the spreadsheet to generate new coupons. A custom WP CLI script seemed much easier to manage.

WP CLI script to generate coupons

As you can see in the screenshot, the WP CLI prompts for the coupon code to duplicate. If the string “UNQCODE” is anywhere in the coupon code, it will be replaced with a unique random string of the same length.

The script also outputs all the generated coupon codes and URLs and saves it to a csv log file.

Feel free to check out the code and adapt it for your own use!

https://gist.github.com/devinsays/9e6030dec131366d2eadca4174f82d57

Leave a Reply