php - 在 Woocommerce 中检查产品类别的购物车项目

标签 php wordpress woocommerce cart custom-taxonomy

在 woocommerce 中,我尝试使用以下方式检查特定产品类别的购物车项目:

add_action('woocommerce_before_cart', 'fs_check_category_in_cart');
function fs_check_category_in_cart() {
    // Set $cat_in_cart to false
    $cat_in_cart = false;
    // Loop through all products in the Cart        
    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        $product = $cart_item['data'];
        echo '<pre>',print_r($product),'</pre>';
        // If Cart has category "download", set $cat_in_cart to true
        if ( has_term( 'downloads', 'product_cat', $product->get_id() ) ) {
            $cat_in_cart = true;
            break;
        }
    }
    // Do something if category "download" is in the Cart      
    if ( $cat_in_cart ) {

        // For example, print a notice
        wc_print_notice( 'Category Downloads is in the Cart!', 'notice' );
        // Or maybe run your own function...
        // ..........
    }
}

我一直无法实现它。当我 print_r( $product ) 时进一步检查 数组的末尾看起来像:

            [current_class_name:WC_Data_Store:private] => WC_Product_Data_Store_CPT
            [object_type:WC_Data_Store:private] => product-simple
    )

    [meta_data:protected] => 
)
1

数组末尾的这个 1 将其自身附加到我尝试引用的任何变量。所以我得到了

downloads1 

如果有人知道这个数字可能来自哪里,它让我感到压力很大!

仅作记录,还执行 print_r( $woocommerce ) 在数组末尾有 1。

感谢任何帮助。

最佳答案

使用 WordPress 检查购物车项目中的产品类别 has_term()条件函数,您也需要使用 $cart_item['product_id'] 来处理检查产品变体中的产品类别。

这样它会检查产品类别的父变量产品,因为产品变体类型不处理任何自定义分类。所以现在它适用于所有情况。

因此您重新访问的代码将是:

add_action('woocommerce_before_cart', 'check_product_category_in_cart');
function check_product_category_in_cart() {
    // HERE set your product categories in the array (can be IDs, slugs or names)
    $categories = array('downloads');
    $found      = false; // Initializing

    // Loop through cart items      
    foreach ( WC()->cart->get_cart() as $cart_item ) {
        // If product categories is found
        if ( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ) {
            $found = true; // Set to true
            break; // Stop the loop
        }
    }

    // If any defined product category is found, we display a notice
    if ( $found ) {
        wc_print_notice( __('Product Category "Downloads" is in Cart items!'), 'notice' );
    }
}

代码进入事件子主题(或事件主题)的 function.php 文件。经过测试并有效。

关于php - 在 Woocommerce 中检查产品类别的购物车项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51136303/

相关文章:

css - 在 WordPress 中制作可堆叠的两列

html - 来自父级的子主题 style.css 不传输

php - Woocommerce - 显示循环内的变化

php - 如果未登录,则仅在购物车页面上显示最后添加的项目

java - 需要从 PHP 翻译成 Java

php - 将数组拆分为多个部分并输出带有值列表的字符串

php - Yii2:发布复杂模型

mysql - WordPress docker 容器不以 mysql :latest image 开头

javascript - Yii ajaxSubmitButton 客户端验证问题

javascript - 覆盖 WooCommerce 前端 Javascript