Woocommerce - 从类别中删除产品

Woocommerce - remove product from category

我正在尝试执行以下操作,但我受困于编码。 希望有人能帮我解决这个问题。

在 Woocommerce 中(在产品编辑页面上)我可以选择产品所属的类别。 我做了一个代码,当有特定条件时,产品将在保存时被放在一个额外的类别 'Aanbiedingen' (id=87) 中。

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

现在我想要一个代码,其中(保存后)产品将从 'Aanbiedingen' 类别中删除,但它仍将在其他类别中。

示例:产品属于类别 'Aanbiedingen'、'Comfort'、'Therapie' 和 'Warmtezakken' 有人可以帮我提供一个代码,其中(保存后)产品只会在 'Comfort'、'Therapie' 和 'Warmtezakken' 中吗?

我想这与使用 wp_get_object_terms 获取类别、删除值 'Aanbiedingen'(或 id 87)并使用 wp_set_object_terms?[=13= 保存此更改后的数组有关]

我尝试了几件事,但无法完成。 有人可以帮我吗?

您只需使用 wp_remove_object_terms($post_id, $terms, $taxonomy) 函数从您的对象中删除特定类别术语 ID(在本例中为产品自定义 post 类型)。

作为旁注,您还想使用 isset() 来检查 $_POST 变量,而不是 !empty() - 如果值不在 POST 的值

// 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' );
}