如果购物车中有某种类别的产品,我试图触发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”产品,我想要一个不错的回音!
谢谢!
最佳答案
根据Barrell的建议编辑了我的代码,并回显“Bingo”!
就像魅力一样工作,下面是代码:
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;
}
希望能对某人有所帮助!
关于php - 根据类别名称woocommerce检查购物车中的产品吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22571887/