根据类别名称woocommerce检查购物车中的产品吗? [英] Checking products in cart based on category name woocommerce?
本文介绍了根据类别名称woocommerce检查购物车中的产品吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果购物车中有某种类别的产品,我正在尝试触发echo语句,这是我的代码:
I'm trying to trigger an echo statement if a certain category of product is in my cart, here's my code:
<?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"产品,我想要一个不错的回音!
Any idea as to what i'm doing wrong? I do have 'name_of_category' products in my cart, i'd like a nice Yes echoed!
谢谢!
推荐答案
按照Barrell的建议编辑了我的代码并回显'Bingo'!
Edited my code following Barrell's advice and echo 'Bingo'!
就像一个咒语一样工作,这是代码:
Works like a charm, here's the code:
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;
}
希望可以帮助某人!
这篇关于根据类别名称woocommerce检查购物车中的产品吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文