Checking products in cart based on category name woocommerce?(根据类别名称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"产品,我想要一个不错的 Yes 回应!
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 的建议编辑了我的代码并回应了宾果游戏"!
Edited my code following Barrell's advice and echo '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;
}
希望能帮到人!
这篇关于根据类别名称woocommerce检查购物车中的产品?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:根据类别名称woocommerce检查购物车中的产品?
基础教程推荐
猜你喜欢
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- 在多维数组中查找最大值 2021-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01