php - 在 Woocommerce 中将特定类别中的产品的项目数量设置为“x”的倍数
问题描述
我在网上找到了一个片段,它允许您在购物车中将最低购买量设置为多个“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”。
其他类别的所有产品也可以少量购买。
解决方案
更新 (也扩展到父产品类别)
尝试以下方法,使您的代码仅适用于特定产品类别:
// 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 文件中。测试和工作。
推荐阅读
- app-config - 当我禁用 sql server 时,运行 c# app 的 .exe 文件会导致错误
- mysql - node.js中的数据库连接,多个脚本文件
- ios - 如何在 IOS 中将浮动操作按钮带出应用程序并使其运行可见、可移动和可点击?
- flutter - 如何使用可以处理来自服务器的最新更新的 Riverpod 制作当前用户数据提供者?
- php - 在不使用 PHP 库的情况下签署 PDF(多重签名)
- sql - 从另一个表的多条记录更新一个表中的一条记录。其中一个表的列名是另一个表的字段
- azure - Azure:New-AzCdnProfile:操作返回无效状态代码“BadRequest”
- gis - 在 OpenLayers 中的 EPSG:25832 中显示矢量切片
- ios - 显示具有其他工作表作为父工作表的工作表时,SwiftUI TextField 第一响应者不起作用
- html - css使用颜色从继承颜色,到另一个属性