php – 计算特定产品类别的购物车项目
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了php – 计算特定产品类别的购物车项目,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1807字,纯文字阅读大概需要3分钟。
内容图文
![php – 计算特定产品类别的购物车项目](/upload/InfoBanner/zyjiaocheng/754/fde24b22c1f640d3ac0121c09869eae7.jpg)
我试图从WooCommerce中的特定产品类别获取购物车中的商品数量.
我正在为酿酒厂做一个网站.它含有酒精和非酒精产品.所有的葡萄酒都属于’葡萄酒’或类别ID 34的主要类别,其下有许多子类别和产品.
对于任何属于此类别的东西……我需要知道此类别下购物车中有多少件物品.如果有六瓶葡萄酒,无论它们是相同的产品ID还是6种不同的产品ID.我需要从’wine’类别或34类别ID中获得6个数字.
我试过这个没有成功.
我是WooCommerce的新手,也是面向对象的新手.
谢谢
function cat_cart_count( $cat_name ) {
// $cat_name variable is for you normally "tshirts" or "shorts"
global $woocommerce; $cat_count = 0;
// For each product in the cart
foreach(WC()->cart->get_cart() as $cart_item_key => $values) {
$_product_id = $values['product_id']; // product ID
$_product_qty = $values['quantity']; // product quantity
// Getting categories of the product (could be more than one)
$terms = get_the_terms( $_product_id, 'product_cat' );
// Checking this product has a category
if ( $terms && ! is_wp_error( $terms ) ) {
$term_name = array();
// For each category of that product
foreach($terms as $term) {
// Adding the category name to an array
$term_name[] = $term->name;
// if the product has $cat_name category
if ( in_array( $cat_name, $term_name ) ) {
// add 1 x product quantity to the count
$cat_count =+ 1 * $_product_qty;
}
}
}
}
解决方法:
WordPress条件函数has_term()接受类别ID,段塞,名称或该值的数组.
所以这是做到这一点的简单方法.您的代码将更紧凑,更轻便.您可以直接使用您的类别ID 34.
这是你的功能:
function cat_cart_count( $cat_name ) {
$cat_count = 0;
// Iterating through each cart item
foreach(WC()->cart->get_cart() as $cart_item)
if( has_term( $cat_name, 'product_cat', $cart_item['product_id']))
$cat_count += $cart_item['quantity'];
return $cat_count;
}
此代码经过测试且功能齐全.
Usage of your function using for example
echo
to display the value for34
category ID:06001
内容总结
以上是互联网集市为您收集整理的php – 计算特定产品类别的购物车项目全部内容,希望文章能够帮你解决php – 计算特定产品类别的购物车项目所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。