【发布时间】:2017-03-26 18:59:32
【问题描述】:
我试图阻止用户将多个特定类别的商品添加到他们的购物车中。我找到了那个功能:
function cart_has_licence_in_it()
{
//Check to see if user has product in cart
global $woocommerce;
//assigns a default negative value
$product_in_cart = false;
foreach ($woocommerce->cart->get_cart() as $cart_item_key => $values) {
$_product = $values['data'];
$terms = get_the_terms($_product->id, 'product_cat');
if ($terms) {
foreach ($terms as $term) {
$_categoryid = $term->term_id;
if ($_categoryid === 23) {
$product_in_cart = true;
}
}
}
}
return $product_in_cart;
}
为此,我刚刚将类别 ID 号更改为 23。 现在我想检查购物车是否已经有该类别的商品,如果有,请从购物车中删除该商品并显示一条消息:
add_filter( 'woocommerce_add_cart_item_data', 'woo_custom_add_to_cart' );
function woo_custom_add_to_cart( $cart_item_data ) {
global $woocommerce;
$categorie = get_the_terms($cart_item_data->id, 'product_cat');
$_lacat = $categorie->term_id;
if (($_lacat===23)&&(cart_has_licence_in_it())) {
wc_add_notice('You cannot add this license to your cart because there is already another license in it. Please remove the other license from your cart first.', 'error' );
$woocommerce->cart->remove_cart_item($cart_item_data->id);
}
else return $cart_item_data;
}
但它不起作用,我什至没有收到消息。
由于我是一般的 WordPress 和 PHP 编码新手,我很确定我的代码中有很多错误。
【问题讨论】:
标签: woocommerce