-2

I need something like this :

It is possible to set that when we have last 5 pcs on stock , some user role (wholesale) cant order that product ?

For example if we set quantity to 6 pcs than wholesale customer can will order only 1 pcs to stay minimum there 5 pcs and if is lower than 5 pcs than wholesale customer cant order than product ?

Lukas
  • 11
  • 1

1 Answers1

0

I don't know if you requirement is feasible or not. But i have a logic (which may or mayn't be the proper way)

  • get stock quantity and user role on clicking add to cart button
  • Check if user role is wholesale customer and stock quantity is the required one
  • if yes then block product from being added to cart

This is the basic implementation of the above logic. I have just checked the code and found that product is not added to cart. You can build on the code to meet your requirements.

function stock_quantity_validation($valid, $product_id, $quantity){

  $qty = 7; // Your required stock quantity
  if( is_user_logged_in() ) {
    $user = wp_get_current_user();
    $roles = ( array ) $user->roles;
    if ( in_array( 'wholesale_customer', $roles ) ) {
      $stock = get_post_meta( $product_id, '_stock', true ); // Getting stock quantity of product
      if($stock < $qty){
        $valid = false;
      }
    }
  }
  return $valid;

}
add_filter('woocommerce_add_to_cart_validation','stock_quantity_validation', 10, 3);
melvin
  • 2,571
  • 1
  • 14
  • 37
  • Thank you for your answer but this is not working for me. after i add this my cart is not working and i cant add nothing the cart :/ – Lukas Mar 24 '19 at 08:22
  • ok let me check. You have to edit this code according to your requirements – melvin Mar 24 '19 at 08:33
  • I have just checked and its working. The above code works (blocks add to cart) only if user role is wholesale customer and stock quantity is greater than 7. I have checked the code with storefront theme and it's working fine (product is being added to cart) – melvin Mar 24 '19 at 08:36