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 http://example.com/wp-admin/post.php?post=123&action=edit – 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:
1 2 |
<?php wp_set_object_terms( $product_id, $term_id, 'product_cat' ); |
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:
1 2 3 |
<?php $term_ids = [ 10, 12, 18 ]; wp_set_object_terms( $product_id, $term_ids, 'product_cat' ); |
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:
1 2 3 4 5 6 7 8 |
<?php $term_ids = []; $terms = wp_get_object_terms( $product_id, 'product_cat' ); if ( count( $terms ) > 0 ) { foreach( $terms as $item ) { $term_ids[] = $item->term_id; } } |
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:
1 2 3 |
<?php $term_ids[] = $term_id; wp_set_object_terms( $product_id, $term_ids, 'product_cat' ); |
You got it!
What if you want to create a brand new category? Well,
2 Comments
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!