繁体   English   中英

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

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

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

我在我的函数中创建了以下 PHP 代码。php 用于我的 WooCommerce 商店:

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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM