How to add a category programmatically to a woocommerce product?

Member

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

How to add a category programmatically to a woocommerce product?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elise_daugherty , a year 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.

Related Threads:

How to remove product-category from urls in woocommerce?
How to show product parent category in woocommerce?
How to set woocommerce product attribute programmatically?
How to get current product category name in woocommerce?
How to change product category slug in bulk in woocommerce?
How to add product sorting dropdown in woocommerce?