【问题标题】:Checking cart items for a product category in Woocommerce在 Woocommerce 中检查产品类别的购物车项目
【发布时间】:2018-12-10 16:32:33
【问题描述】:

在 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。

感谢任何帮助。

【问题讨论】:

  • 这是由于echo '&lt;pre&gt;',print_r($product),'&lt;/pre&gt;'; 构造。您要么希望 echo '&lt;pre&gt;',print_r($product, true),'&lt;/pre&gt;'; 将 print_r return 设为字符串而不是直接输出,要么希望使用单独的语句 echo '&lt;pre&gt;'; print_r($product); echo '&lt;/pre&gt;';
  • 尝试获取这样的产品 ID $cart_item['product_id'] 而不是 $cart_item['data']

标签: php wordpress woocommerce cart custom-taxonomy


【解决方案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 文件中。经过测试并且可以工作。

【讨论】:

  • 啊,你的英雄!非常感谢!总结一下,数字 1 正在打印,因为我错误地回显了数组?
猜你喜欢
  • 2019-06-15
  • 2017-04-27
  • 2014-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多