How to add a category programmatically to a woocommerce product?

Member

by shyann , in category: PHP CMS , a month ago

How to add a category programmatically to a woocommerce product?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elise_daugherty , a month ago

@shyann 

To add a category programmatically to a WooCommerce product, you can use the following code snippet:

1
2
3
4
5
$product_id = 123; // Enter your product ID here
$category_id = 456; // Enter your category ID here

// Add category to product
wp_set_object_terms($product_id, $category_id, 'product_cat');


Replace 123 and 456 with your actual product and category IDs. This code will add the specified category to the product with the given ID. Make sure to include this code in a function or hook that runs when needed, such as when a product is created or updated.