WooCommerce使用相同的自定义参数在购物车中添加产品
问题描述:
在我的商店中,我的产品带有“添加到购物车”按钮前的复选框。 如果客户选中此复选框并添加到购物车,则会将该值发送到购物车会话。WooCommerce使用相同的自定义参数在购物车中添加产品
我的复选框的代码:
<input type="checkbox" id="check" name="check" value="colissimo">
要输出我的复选框值我在cart.php
使用:
$cart_item['check'];
我想创造签微型车,如果有一个函数带有该复选框的产品。
出现情况1:
顾客在选中复选框的情况下将产品添加到购物车。 客户转到其他产品。 在产品中他们有一个复选框,但客户没有检查并添加到购物车。
购物车返回false,因为它没有被选中。
出现情况2: 客户添加到购物车的产品与复选框不勾选。 客户转到其他产品。 在产品中,他们有一个复选框,但客户检查箱并添加到购物车。
购物车因检查而返回false。
我想用下面的代码来实现这一点,但它不工作:
function is_product_the_same_cat($valid, $product_id, $quantity) {
global $woocommerce;
if($woocommerce->cart->cart_contents_count == 0){
return true;
}
foreach ($woocommerce->cart->get_cart() as $cart_item_key => $values) {
$_product = $values['data'];
$items = $woocommerce->cart->get_cart();
$target_terms = $woocommerce->cart->get_cart();
foreach ($items as $item) {
$cat_ids[] = $cart_item['check'];
}
foreach ($target_terms as $term) {
$target_cat_ids[] = $cart_item['check'];
}
}
$same_cat = array_intersect($cat_ids, $target_cat_ids);
print_r ($same_cat);
if(count($same_cat) > 0) return $valid;
else {
wc_add_notice('This product have not the same parameter!', 'error');
return false;
}
}
add_filter('woocommerce_add_to_cart_validation', 'is_product_the_same_cat',10,3);
感谢的对你有所帮助。
答
function is_product_the_same_cat($valid, $product_id, $quantity) {
global $woocommerce;
//si panier vide ok
if($woocommerce->cart->cart_contents_count == 0){
return true;
}
foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) {
$cat_ids[] = $cart_item['check'];
}
$coli = $cat_ids;
if ((in_array("colissimo", $coli))){
if ((in_array("colissimo", $coli)) && (($_POST['check'])==='colissimo')){
return $valid;}
else {
wc_add_notice('Les produits Colissimo font l\'objet d\'un panier séparé !', 'error');
return false;
}
}else{
if(!isset ($_POST['check'])){return $valid;}
else {
wc_add_notice('Les produits Colissimo font l\'objet d\'un panier séparé !', 'error');
return false;
}
}
}
add_filter('woocommerce_add_to_cart_validation', 'is_product_the_same_cat',10,3);