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:
1 2 3 4 5 |
<?php $term = wp_insert_term( 'FooBar category', 'product_cat', [ 'description'=> 'FooBar Category description', 'slug' => 'foobar-category' ] ); |
You should get something like this:
1 2 3 4 5 |
Array ( [term_id] => 509 [term_taxonomy_id] => 509 ) |
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:
1 2 3 4 5 6 7 8 9 10 |
<?php $term = wp_insert_term( 'FooBar category', 'product_cat', [ 'description'=> 'FooBar Category description', 'slug' => 'foobar-category' ] ); if ( is_wp_error( $term ) ) { $term_id = $term->error_data['term_exists'] ?? null; } else { $term_id = $term['term_id']; } |
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.
2 Comments
Vinod Dalvi
Hi,
Thanks for sharing this useful information.
VD
John Smubble
Thank you very much for this great tutorial. Waiting for next post.