本文介紹了對于 Woocommerce 中特定類別的產品,將項目數量設置為“x"的倍數的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我在網上找到了一個片段,它允許您在購物車中將最低購買量設置為多個6".
I found online a snippet that allows you to set in the cart a minimum purchase to multiple quantities of "6".
這是:
add_action( ‘woocommerce_check_cart_items’, ‘woocommerce_check_cart_quantities’ );
function woocommerce_check_cart_quantities() {
$multiples = 6;
$total_products = 0;
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$total_products += $values['quantity'];
}
if ( ( $total_products % $multiples ) > 0 )
wc_add_notice( sprintf( __('You need to buy in quantities of %s products', 'woocommerce'), $multiples ), 'error' );
}
我希望此規則僅對屬于特定類別且id = 35"的產品有效.
I want this rule to be valid only for products belonging to a specific category, with "id = 35".
其他類別的所有產品也可以小批量購買.
All products in other categories can also be purchased in smaller quantities.
推薦答案
更新 (也擴展到父產品類別)
請嘗試以下操作,使您的代碼僅適用于特定產品類別:
Try the following that will make your code work only for a specific product category:
// Custom conditional function that checks also for parent product categories
function has_product_category( $product_id, $category_ids ) {
$term_ids = array(); // Initializing
// Loop through the current product category terms to get only parent main category term
foreach( get_the_terms( $product_id, 'product_cat' ) as $term ){
if( $term->parent > 0 ){
$term_ids[] = $term->parent; // Set the parent product category
$term_ids[] = $term->term_id;
} else {
$term_ids[] = $term->term_id;
}
}
return array_intersect( $category_ids, array_unique($term_ids) );
}
add_action( 'woocommerce_check_cart_items', 'woocommerce_check_cart_quantities' );
function woocommerce_check_cart_quantities() {
$multiples = 6;
$total_products = 0;
$category_ids = array( 35 );
$found = false;
foreach ( WC()->cart->get_cart() as $cart_item ) {
if ( has_product_category( $cart_item['product_id'], $category_ids ) ) {
$total_products += $cart_item['quantity'];
$found = true;
}
}
if ( ( $total_products % $multiples ) > 0 && $found )
wc_add_notice( sprintf( __('You need to buy in quantities of %s products', 'woocommerce'), $multiples ), 'error' );
}
代碼位于您的活動子主題(活動主題)的 function.php 文件中.經測試有效.
Code goes in function.php file of your active child theme (active theme). Tested and works.
這篇關于對于 Woocommerce 中特定類別的產品,將項目數量設置為“x"的倍數的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!