【问题标题】:WooCommerce: Custom Text Based On Cart Item Count of Certain CategoryWooCommerce:基于特定类别的购物车项目计数的自定义文本
【发布时间】:2020-12-25 21:19:34
【问题描述】:

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

我在我的 Function.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”。

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

【问题讨论】:

    标签: php wordpress woocommerce cart


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-18
      • 2019-12-19
      • 2019-01-17
      • 1970-01-01
      • 1970-01-01
      • 2015-12-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多