1

Is is possible to remove all the categories from a product in WooCommerce?

I have written a script which is run every time when a product is added/updated via WP-All-Import, but there are some wrong categories on the products, which I want to clean, deleting all the categories or products is not an option, so I want clear the categories on the products and let my script decide which categories to add to this product.

2 Answers 2

1

I have found the solution, actually it is very simple:

$terms = get_the_terms($product_id, 'product_cat');
foreach($terms as $term){
    wp_remove_object_terms($product_id, $term->term_id, 'product_cat');
}

This code get all the therms with the 'product_cat' taxonomy, with a foreach loop I remove all the items.

2
  • where do you put this code?
    – d-cmst
    Commented Jun 27, 2017 at 14:05
  • @domenicocamasta I have written an plugin which runs every time when an product is added via WP All Import, there have I added this code before the new categories are processed.
    – NVO
    Commented Jun 27, 2017 at 14:23
0

You could wipe all terms from a product using the wp_set_post_terms function. Setting the append argument to false ensures that all terms are overwritten.

For example:

wp_set_post_terms( $product_id, array(), 'product_cat', false );

More information on the wp_set_post_terms function: https://developer.wordpress.org/reference/functions/wp_set_post_terms/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.