Development,  Woocommerce,  WordPress

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.


  • Kil

    Si envías True como parámetro final, no te borra las demás categoría que tenga el producto.

    wp_set_object_terms( $product_id, $term_id, ‘product_cat’ , true);

    • Łukasz Nowicki

      This is Spanish language so I let myself to translate. Kil wrote that if you add boolean true as a third parameter, existing categories won’t be erased. That is true 🙂 Third parameter stands for ‘append’ and is default false. I didn’t mention it, because I wrote about assigning category or categories in context of my previous article about adding products programmatically. Thank you anyway for your support!

Leave a Reply

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