0

我正在尝试检查客户在每次迭代中添加了多少特定产品类别的产品(即添加了 1 个或多个,或删除了 1 个或多个)。我想将它传递给前端并存储在 localStorage 中,以便我可以使用它设置 cookie。而且我需要能够在它发生变化时检查它。

最初,我尝试将此映射到添加到购物车按钮的单击功能。这不起作用,因为您可以单击,但添加到购物车可能不成功(库存不足,价格太低,因为我正在尝试实现按需付费组件)。

我找到了各种方法来尝试列出所有产品类别或检索当前项目,但无法准确找到我想要的方法。

在我的购物车对象中,我首先尝试:


echo $product->get_categories( ', ', '<span class="posted_in hidden">' . _n( '', '', sizeof( get_the_terms( $post->ID, 'product_cat' ) ), 'woocommerce' ), '</span>' );

但这似乎只适用于产品页面。

然后这看起来很有希望:


wp_list_categories( array('taxonomy' => 'product_cat', 'title_li'  => '') );

这将返回所有产品类别

和这个:


echo wc_get_product_category_list( $cart_item['product_id'] );

这似乎检索了第一个(或唯一一个)产品类别,并且在购物车页面上没有返回任何内容。

基本上我正在寻找

产品类别: product_a, 数量:2

或与此非常相似的东西。我的目标是限制用户在一次交易中可以购买的产品数量,但仅限于一个产品类别。IE 如果不在受限类别中,他们可以购买无限的产品。

希望这是有道理的。

更新

我发现几乎可以工作

<?php
    // holds checks for all products in cart to see if they're in our category
    $category_checks = array();

    // check each cart item for our category
    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {

        $product = $cart_item['data'];
        $product_in_cat = false;

        // replace 'membership' with your category's slug
        if ( has_term( 'instant-print', 'product_cat', $product->id ) ) {
            $product_in_cat = true;
        }

        array_push( $category_checks, $product_in_cat );
    }

    // if all items are in this category, do something
    if ( ! in_array( false, $category_checks, true ) ) {
        echo 'items in category' . count($category_checks);
    } else {
        echo 'No items in category' . count($category_checks);
    }
?>

唯一的问题是数组的长度似乎适用于购物车中的所有产品,而不是与我的产品类别“即时打印”匹配的产品。

4

1 回答 1

0

好的,我有一些正在工作的东西,而且相对简单。

我现在正在使用:

<?php
    // holds checks for all products in cart to see if they're in our category
    $category_checks = array();

    // check each cart item for our category
    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {

        $product = $cart_item['data'];
        $product_in_cat = false;

        // replace 'membership' with your category's slug
        if ( has_term( 'instant-print', 'product_cat', $product->id ) ) {
            $product_in_cat = true;
        }

        array_push( $category_checks, $product_in_cat );
    }

   $filtered_array = count(array_filter($category_checks));
   echo '<span class="limited-product-count hidden">' . $filtered_array . '</span>'

?>
于 2021-02-18T23:09:08.717 回答