php - 计算特定产品类别的购物车项目

标签 php wordpress woocommerce cart custom-taxonomy

我试图从 WooCommerce 中的特定产品类别中获取购物车中的商品数量。

我正在为一家酿酒厂制作网站。它有酒精和非酒精产品。所有 Wine 都属于“ Wine ”或类别 ID 34 的主要类别,其下有许多子类别和产品。

对于属于该类别的任何东西...我需要知道该类别下购物车中有多少件商品。如果有六瓶酒,无论它们都是相同的产品 ID 还是 6 个不同的产品 ID。我需要从“ Wine ”类别或类别 ID 为 34 的类别中获取数字 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、slug、名称或该值的数组。

所以这是完成它的更短、更简单的方法。您的代码将更加紧凑和轻便。您可以直接使用您的类别 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 for 34 category ID:

echo cat_cart_count( 34 );

关于php - 计算特定产品类别的购物车项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41025474/

相关文章:

wordpress - 如何使用 WooCommerce 更改要在 google 上编制索引的内容?

php - 'un-filled' 表单输入是否会减慢网站速度?

php - 检查电子邮件是否存在php

php - 如何在不使用限制超过 1 的 MySql 查询循环的情况下获取最后一行的值

woocommerce - 如何在 Woocommerce 中保存以前的产品库存数量?

wordpress - 在自定义感谢页面上显示 Woocommerce 订单详细信息

javascript - 如何禁用旧浏览器的网站?

html - 网站上的图片未在 Chrome 上显示

php - WORDPRESS UPDATE DB 方法未被调用

css - Ubermenu DROP UP 子菜单而不是下拉 - WordPress 插件