![](/img/trans.png)
[英]WooCommerce checkout fee based on cart item count with category excluded
[英]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.