user3406217
user3406217

Reputation:

Woocommerce - remove product from category

I'm trying to do the following, but I'm stuck with coding. Hope someone can help me out here.

In Woocommerce (on the product-edit page) I can choose in which category the product will be. I made a code where the product will be put in an extra category 'Aanbiedingen' (id=87) upon save, when there are certain conditions.

if ( !empty ($_POST['sale_enddate']) && ($_POST['sale_begindate']) ) {
    $cat_ids = array( 87 );
    wp_set_object_terms( $product_id, $cat_ids, 'product_cat', true );
    }   

Now I would like to have a code where (upon save) the product will be removed from the 'Aanbiedingen' category, but it will still be in other categories.

Example: The product is in category 'Aanbiedingen', 'Comfort', 'Therapie' and 'Warmtezakken' Can someone help me with a code where (upon save) the product will only be in 'Comfort', 'Therapie' and 'Warmtezakken' ?

I guess it has something todo with getting categories with wp_get_object_terms , removing value 'Aanbiedingen' (or id 87) and saving this altered array back with wp_set_object_terms?

I tried several things, but I can't get it done. Can someone please help me?

Upvotes: 2

Views: 3588

Answers (1)

doublesharp
doublesharp

Reputation: 27677

You just need to use the wp_remove_object_terms($post_id, $terms, $taxonomy) function to remove the specific category term ID from your object (in this case a Product custom post type).

As a side note, you also want to use isset() to check for the $_POST variable, instead of !empty() - you will get a warning using the latter method if the value isn't in the POST'd values

// category ID array used for both adding & removing
$cat_ids = array( 87 );

if ( isset( $_POST['sale_enddate'] ) && $_POST['sale_begindate'] ) {
    // conditions met for adding product to category
    wp_set_object_terms( $product_id, $cat_ids, 'product_cat', true );
} else {
    // otherwise remove it
    wp_remove_object_terms( $product_id, $cat_ids, 'product_cat' );
}

Upvotes: 3

Related Questions