php - 在 Woocommerce 中禁用特定用户角色的延期交货
问题描述
在 woocommerce 中,我使用延期交货复选框将我的产品置于延期交货状态。现在一切都在延期交货,我想为普通客户禁用延期交货(并让它为其他用户角色,如批发客户)。
我有以下代码,但是当我将其添加为插件时,我无法将某些内容添加到我的购物车(我可以按下添加到购物车按钮,但购物车保持为空):
/*Single product page: out of stock when product stock quantitiy is lower or equal to zero AND customer is not wholesale_customer.*/
add_filter('woocommerce_product_is_in_stock', 'woocommerce_product_is_in_stock' );
function woocommerce_product_is_in_stock( $is_in_stock ) {
global $product;
$user = wp_get_current_user();
$haystack= (array) $user->roles;
$target=array('wholesale_customer');
if($product->get_stock_quantity() <= 0 && count(array_intersect($haystack, $target)) == 0){
$is_in_stock = false;
}
return $is_in_stock;
}
/*Single product page: max add to cart is the product's stock quantity when customer is not wholesale_customer.*/
function woocommerce_quantity_input_max_callback( $max, $product ) {
$user = wp_get_current_user();
$haystack= (array) $user->roles;
$target=array('wholesale_customer');
if(count(array_intersect($haystack, $target)) == 0){
$max= $product->get_stock_quantity();
}
return $max;
}
add_filter( 'woocommerce_quantity_input_max', 'woocommerce_quantity_input_max_callback',10,2);
解决方案
尝试改用woocommerce_is_purchasable( $is_purchasable, $product )
过滤器。它应该返回真或假。
此外,您也不需要花这么多精力来获取用户的角色。一个简单的if ( current_user_can( 'wholesale_customer' ) )
就足够了。
所以,像:
function my_is_purchasable( $is_purchasable, $product ) {
if ( current_user_can( 'wholesale_customer' ) ) {
return true;
} elseif ( $product->get_stock_quantity() <= 0 ) {
return false;
} else {
return $is_purchasable;
}
}
add_filter( 'woocommerce_is_purchasable', 'my_is_purchasable', 10, 2 );
注意:这只是为了演示,因为我现在不在办公桌前,所以无法为您正确测试它。
推荐阅读
- java - 为什么每次都执行 SELECT SQL 甚至在 Hibernate 中配置了 SecondLevel 和 Query Cache
- javascript - 在 Select2 v3 上选择值后隐藏虚拟键盘
- swift - 错误是“AuthDataResult”类型的值没有成员“uid”?
- c# - 优化SqlCommand的使用
- c - 值为 17 的套接字协议是什么?
- javascript - JS使用parseFloat,十进制中有很多0
- python - python pandas groupby agg 得到 lag1
- css - 带有 CSS 的圆形滑块
- ruby-on-rails - Rails 5.1 - 按关联值排序的显示列表
- python - 如何使用终端输入作为 Python 参数?