Assign woocommerce product categories programmatically

How to assign categories for your Woocommerce products programmatically?
Well, it isn’t that hard.
First of all, you must know the ID of your product. If you insert your product programmatically, it is easy, you got it. If not, you can see ID for many ways, for example in your edit screen (something like – 123 is your product ID).

Let’s assume you’ve got your product ID in the $product_id variable.

Now, you must decide if you want to assign product to existing category or create category by yourself? Well, if you already got category, you need your term ID. How to get it? Go to product categories list and hover your mouse over ‘Edit’ link for example. You will see something like that: http://example/wp-admin/term.php?taxonomy=product_cat&tag_ID=555&post_type=product… – 555 is your term ID.

Let’s assume you’ve got your product ID in the $term_id variable.

So, now it is very easy, write something like this:

And that’s it! Your product is assigned to proper category.

What if I need to assign product to two, three or even more categories at once?

Well, it is also pretty easy. Just don’t use term ID as an integer, use it in the array. Something like that:

Not a very hard thing to do. Now what if you want to assign certain category to a product, but you don’t want to lose already attached categories? It’s not hard, too!

First, we need to retrieve existing categories. Let’s write something like this:

Now, we’ve got existing categories in $term_ids array. Or an empty arrow if the product has no categories. Then simply add your $term_id to the array and assign it to the product like this:

You got it!

What if you want to create a brand new category? Well, I will write about it later (probably tomorrow morning) it is here, waiting for you: Add woocommerce category programmatically. Remember that you need to hook this operations! Action ‘init’ would be a good place to do that.

Be the first to comment

Leave a Reply

Your email address will not be published.