我有一些購物車邏輯,如果購物車中有來自冷藏類別的1 件商品,它會檢查至少 3 件商品。- 這是經過測驗和作業的。
但是,如果我從不同的類別(環境)向購物車中添加另一個專案,并且現在購物車中既有冷藏專案,也有環境專案,則不再應用該規則。
如果購物車中還有環境商品,我如何確保應用 3 冷藏最低規則?
// Set minimum quantity per product before checking out
add_action( 'woocommerce_check_cart_items', 'protein_set_min_total' );
function protein_set_min_total() {
// Only run in the Cart or Checkout pages
if( is_cart() || is_checkout() ) {
global $woocommerce, $product;
$i=0;
// Set minimum product cart total
//And initialise product catergory counters
$minimum_protein = 3;
$total_protein = 0;
$cat_in_cart = false;
foreach ( $woocommerce->cart->cart_contents as $product ) :
if ( has_term( 'chilled', 'product_cat', $product['product_id'] ) ) {
$total_protein = $product['quantity'];
}
endforeach;
if (has_term( 'chilled', 'product_cat', $product['product_id'] ) && $total_protein < $minimum_protein) {
wc_add_notice( sprintf( '<strong>A Minimum of %s products are required from The CHILLED category before checking out.</strong>'
. '<br />Current number of Chilled items in the cart: %s.',
$minimum_protein,
$total_protein ),
'error' );
}
//}
}
}
uj5u.com熱心網友回復:
下面的代碼將計算屬于該chilled類別的所有專案。只有當這等于或大于 3 時,才有可能繼續訂購程序。
所以你得到:
function action_woocommerce_check_cart_items() {
// Only run on the cart or checkout pages
if ( is_cart() || is_checkout() ) {
// Minimum
$minimum = 3;
// Category
$category = 'chilled';
// Initialize
$total = 0;
// Loop through cart items
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
// Product id
$product_id = $cart_item['product_id'];
// Has certain category
if ( has_term( $category, 'product_cat', $product_id ) ) {
// Add to total
$total = $cart_item['quantity'];
}
}
// When total is greater than 0 but less than the minimum
if ( $total > 0 && $total < $minimum ) {
// Notice
wc_add_notice( sprintf( __( 'A minimum of %s products are required from the %s category before checking out.', 'woocommerce' ), $minimum, $category ), 'error' );
// Optional: remove proceed to checkout button
remove_action( 'woocommerce_proceed_to_checkout', 'woocommerce_button_proceed_to_checkout', 20 );
}
}
}
add_action( 'woocommerce_check_cart_items' , 'action_woocommerce_check_cart_items', 10, 0 );
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/345946.html
標籤:php WordPress的 求购 大车 查看
