Update wordpress post terms programatically

by danyo   Last Updated May 03, 2018 10:08 AM

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:

<label><input 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)){ ?>

            <label><input name="" type="checkbox" value="" id="cat_term_<?php echo $catTerm->name;?>" name="cat_term[]" checked="checked" /><?php echo $catTerm->name; ?></label><br />             

            <?php } else { ?>

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


            <?php } ?>

            <?php endforeach; ?>
            <?php } ?>


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

    $prod_cats = $_POST['cat_term'];

    wp_set_post_terms( $id, $prod_cats );


}
Tags : categories terms


Answers 1


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

shahpranaf
shahpranaf
May 12, 2014 09:38 AM

Related Questions



set terms to category and subcategory

Updated November 08, 2016 08:03 AM