Development,  Woocommerce,  WordPress

Add woocommerce category programmatically

As I promised in this article Assign woocommerce product categories programmatically, I will explain how to create woocommerce category programmatically.

It is very easy, just use this code:

You should get something like this:

However, sometimes you may get WP_Error. Sometimes, category may already exists. You must check the result, if it isn’t WP_Error object. So, if you need to add category or get existing category ID, use this:

This code uses PHP7 construction (?? – null coalesce operator), you may substitute it with isset when using earlier PHP version (or much better – upgrade your PHP or your hosting operator!)

Remember to wrote this code in the proper hook (I use ‘init’ action). And of course it is better to add categories on plugin activate hook or something similar to avoid adding it many times. Of course it won’t be added (remember, WP_Error object…) but it will consume your application’s time.


Leave a Reply

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