Set item quantity to multiples of “x” for products in a specific category in Woocommerce(对于 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"的倍数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:对于 Woocommerce 中特定类别的产品,将项目数量设
基础教程推荐
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- 在多维数组中查找最大值 2021-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01