Update wordpress post terms programatically

I am currently working with woocommerce for wordpress and making a custom plugin.

I would like to update the product categories manually through my own admin panel, here is what I have so far:

$catTerms = get_terms('product_cat', array('hide_empty' = 0, 'orderby' = 'ASC'));

This gets all product categories when looped.

I then add checkboxs to the items in the loop like this:

labelinput name="" type="checkbox" value="" id="cat_term_?php echo $catTerm-name;?" name="cat_term[]" /?php echo $catTerm-name; ?/label

I then save the terms like this which isn't working:

$prod_cats = $_POST['cat_term'];
wp_set_post_categories( $id, $prod_cats );

I have also tried the following:

wp_set_object_terms( $id, $prod_cats );

And:

wp_set_post_terms( $id, $prod_cats );

Is there something I am doing wrong? Maybe not saving them in the correct way?

Full Code as requested:

?php 
            $cats = array();            
            $product-get_categories();


            //print_r($cats);


             $terms = wp_get_post_terms( get_the_id(), 'product_cat' );


             foreach ($terms as $term){
                 $cats[] =  $term-name;
             }

        print_r($cats);

            ?

            ?php $catTerms = get_terms('product_cat', array('hide_empty' = 0, 'orderby' = 'ASC')); ?
            ?php foreach($catTerms as $catTerm) : ?


            ?php if (in_array($catTerm-name, $cats)){ ?

            labelinput name="" type="checkbox" value="" id="cat_term_?php echo $catTerm-name;?" name="cat_term[]" checked="checked" /?php echo $catTerm-name; ?/labelbr /             

            ?php } else { ?

            labelinput name="" type="checkbox" value="" id="cat_term_?php echo $catTerm-name;?" name="cat_term[]" /?php echo $catTerm-name; ?/labelbr /


            ?php } ?

            ?php endforeach; ?
            ?php } ?


if (isset($_POST['save'])) {
    $id = $_POST['item_id'];

    $prod_cats = $_POST['cat_term'];

    wp_set_post_terms( $id, $prod_cats );


}

Topic terms categories Wordpress

Category Web


Please add taxonomy name in wp_set_post_terms function.

wp_set_post_terms( $id, $prod_cats, 'product_cat' );

Please refer wpcodex wp_set_post_terms

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.