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

Wil*_*l T 2 php wordpress cart custom-taxonomy woocommerce

在 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...
        // ..........
    }
}
Run Code Online (Sandbox Code Playgroud)

我一直无法实现它。当我进一步检查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
Run Code Online (Sandbox Code Playgroud)

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

downloads1 
Run Code Online (Sandbox Code Playgroud)

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

只是为了记录print_r( $woocommerce ),数组末尾还有 1 。

任何帮助表示赞赏。

Loi*_*tec 6

使用 WordPresshas_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' );
    }
}
Run Code Online (Sandbox Code Playgroud)

代码位于活动子主题(或活动主题)的 function.php 文件中。测试和工作。