[英]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. 在Woocommerce中(在产品编辑页面上),我可以选择产品的类别。 I made a code where the product will be put in an extra category 'Aanbiedingen' (id=87) upon save, when there are certain conditions. 我编写了一个代码,在存在某些条件的情况下,将保存该产品并将其放在额外的类别“ 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 );
}
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. 现在,我想要一个代码,该代码将(在保存时)从“ Aanbiedingen”类别中删除该产品,但仍将其归为其他类别。
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' ? 示例:该产品属于“ Aanbiedingen”,“ Comfort”,“ Therapie”和“ Warmtezakken”类别。有人可以帮我提供一个代码,(仅保存时)该产品仅位于“ Comfort”,“ Therapie”和“ 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
? 我猜想这与通过wp_get_object_terms
获取类别,删除值“ Aanbiedingen”(或ID 87)并使用wp_set_object_terms
保存此更改后的数组wp_set_object_terms
吗?
I tried several things, but I can't get it done. 我尝试了几件事,但无法完成。 Can someone please help me? 有人可以帮帮我吗?
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). 您只需要使用wp_remove_object_terms($post_id, $terms, $taxonomy)
函数从对象中删除特定类别术语ID(在这种情况下为Product自定义帖子类型)。
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 附带说明一下,您还想使用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' );
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.