WooCommerce:基于特定类别的购物车项目计数的自定义文本

WooCommerce: Custom Text Based On Cart Item Count of Certain Category

我觉得这不应该那么难,但同时,如果我不能用我的 5 分钟 PHP 知识完成它,它可能不像我期望的那么容易这就是。

我在我的 functions.php 中为我的 WooCommerce 商店创建了以下 PHP 代码:

add_filter('woocommerce_add_to_cart_fragments', 'new_cart_count_fragments', 10, 1);

function new_cart_count_fragments($fragments) {

    if ( WC()->cart->get_cart_contents_count() < 1) {
        $fragments['.cart-count-cat'] = '<span class="count-text">Custom message 1</span>';

    } elseif ( WC()->cart->get_cart_contents_count() == 1 ) {
        $fragments['.cart-count-cat'] = '<span class="count-text">Custom message 2</span>';

    } else {
        $fragments['.cart-count-cat'] = '<span class="count-text">Custom message 3</span>'; 
    }

    return $fragments;
}

代码完成了它应该做的事情。它没有坏,但我想修改它,但似乎无法弄清楚如何。

目前,它会查找购物车数量,如果它小于 1,则会向我的 CSS 类 之一添加一些文本。如果我正好有 1 个,它会显示第二条消息,如果我的购物车中有超过 1 个产品,它会显示最后一条消息。由于片段,所有这些都是动态完成的。

下面是我几个小时以来一直想弄清楚的问题。

我不想查找购物车中的产品总量,而是想指定一个产品类别并让代码查看我的购物车中该特定类别的产品数量只有.

假设我有类别“x”和“y”。

如果我在购物车中有 1 个类别为“x”的产品和另一个类别为“y”的产品,并且代码只计算类别“x”,它应该显示“自定义消息 2”。

我希望这是有道理的,而且实际上并不那么困难。非常感谢任何帮助

试试这个我也刚发现这个希望它还没有被弃用。

add_filter('woocommerce_add_to_cart_fragments', 'new_cart_count_fragments', 10, 1);

function new_cart_count_fragments($fragments) {
   $product_counter = 0;

   foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        
    $product = $cart_item['data'];

    // replace 'x' with your category's slug
    if ( has_term( 'x', 'product_cat', $product->id ) ) {
      $product_counter++;
    }
  }

if ( $product_counter < 1) {
    $fragments['.cart-count-cat'] = '<span class="count-text">Custom message 1</span>';

} elseif ( $product_counter == 1 ) {
    $fragments['.cart-count-cat'] = '<span class="count-text">Custom message 2</span>';

} else {
    $fragments['.cart-count-cat'] = '<span class="count-text">Custom message 3</span>'; 
}

return $fragments;
}