如果某个类别的产品在我的购物车中,我试图触发一条echo声明,这是我的代码:
<?php
//Check to see if user has product in cart
global $woocommerce;
//flag no book in cart
$item_in_cart = false;
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
$terms = get_the_terms( $_product->id, 'product_cat' );
foreach ($terms as $term) {
$_categoryid = $term->term_id;
}
if ( $_categoryid == 'name_of_category' ) {
//book is in cart!
$item_in_cart = true;
}
}
if ($item_in_cart === true) {echo 'YES';}
else {echo 'Nope!';}
?>
知道我做错了什么?我确实有'name_of_category&#39;在我的购物车中的产品,我喜欢很好的回应!
谢谢!
答案 0 :(得分:13)
按照Barrell的建议编辑我的代码并回应&#39;宾果&#39;!
像魅力一样,这里是代码:
function check_product_in_cart() {
//Check to see if user has product in cart
global $woocommerce;
//assigns a default negative value
// categories targeted 17, 18, 19
$product_in_cart = false;
// start of the loop that fetches the cart items
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
$terms = get_the_terms( $_product->id, 'product_cat' );
// second level loop search, in case some items have several categories
foreach ($terms as $term) {
$_categoryid = $term->term_id;
if (( $_categoryid === 17 ) || ( $_categoryid === 18 ) || ( $_categoryid === 19 )) {
//category is in cart!
$product_in_cart = true;
}
}
}
return $product_in_cart;
}
希望能帮助别人!
答案 1 :(得分:1)
function check_product_in_cart() {
//Check to see if user has product in cart
global $woocommerce;
// start of the loop that fetches the cart items
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
$terms = get_the_terms( $_product->id, 'product_cat' );
// second level loop search, in case some items have several categories
// this is where I started editing Guillaume's code
$cat_ids = array();
foreach ($terms as $term) {
$cat_ids[] = $term->term_id;
}
if(in_array(434, (array)$cat_ids) || in_array(435, (array)$cat_ids)) {
//category is in cart!
$product_in_cart = true;
}
}
return $product_in_cart;
}