问题
In woocommerce,I put my products on backordering with the backorder checkbox. Now that everything is on backordering, I want to disable backordering for normal customers (and let it be for other user roles such as wholesale_customer).
I have the following code but when I add it as a plugin, I am unable to add something to my cart (I can push the add to cart button, but the cart stays empty):
/*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);
回答1:
Try using the woocommerce_is_purchasable( $is_purchasable, $product )
filter instead. It should return true or false.
Also, you also don't need to go to such lengths to get the user's role. A simple if ( current_user_can( 'wholesale_customer' ) )
will suffice.
So, something like:
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 );
Note: This is just by way of demonstration, as I can't test it properly for you as I'm not at my desk right now.
回答2:
Try the following code use dedicated woocommerce_product_backorders_allowed
filter hook:
add_filter( 'woocommerce_product_backorders_allowed', 'products_backorders_allowed', 10, 3 );
function products_backorders_allowed( $backorder_allowed, $product_id, $product ){
$user = wp_get_current_user();
$user_roles = (array) $user->roles;
if( in_array( 'customer', $user_roles ) && ! in_array( 'wholesale_customer', $user_roles ) ){
$backorder_allowed = false;
}
return $backorder_allowed;
}
Code goes in function.php file of your active child theme (or active theme). It should works.
来源:https://stackoverflow.com/questions/51615231/disable-backordering-for-a-specific-user-role-in-woocommerce