for the last two days I am trying to find a solution to this little problem. I want to change the categories of certain products programatically, so far I have this

It seems quite logical for example the first few lines

if its a product and its in the category divingsuits then change the category to category with ID 108,

BUT it just does not work, I am so lost, any ideas what I might have overlooked ?

add_action( 'publish_product', 'update_terms' );
function update_terms($post_id) {
$post = get_post( $post_id );

if ( is_product() && has_term( 'divingsuits', 'product_cat' ) ) {
    // TEST 1
$categories = array(108);
wp_set_object_terms( $post_id, $categories , 'product_cat', false );

} elseif ( is_product() && has_term( 'elektro', 'product_cat' ) ) {
// TEST 2
$categories = array(78);
wp_set_object_terms( $post_id, $categories , 'product_cat', false );

} else  {
// TEST 3
$categories = array(115);
wp_set_object_terms( $post_id, $categories , 'product_cat', false );           
  • it is off-topic but obviously is_productis a theme function which should probably not be used on admin side. Commented Jul 17, 2016 at 11:48

1 Answer 1


Your issue here likely is the action 'publish_product' not firing - it only runs when you first create a product, or set a products status from Draft or Pending Review to Publish.

Be aware that wp_set_object_terms will overwrite any other existing category data with the last parameter set to false, in your code those products would end up with only the one new category.

Since you are just changing one category to another is there a reason why your not just giving the existing categories new names and slugs?

You could also just do this through the bulk edit facility - under screen options you can up the view to say 500 products at a time and still will perform ok (depending on your set up could be slow but you'd still get through 10,000+ products in 20 minutes).

Lastly just for future reference all your $category variables are only single values (intergers) so no need for array().

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.