Home / Admin / Prevent Wholesale Customer to Add Product to the Cart If The Product is Low on Stock
Duplicate Snippet

Embed Snippet on Your Site

Prevent Wholesale Customer to Add Product to the Cart If The Product is Low on Stock

Code Preview
php
<?php
// Prevent wholesale customer to add to cart if the product is low on stock
add_filter('woocommerce_is_purchasable', 'wwpp_disable_cart_lowstock', 10, 2 );
add_filter('woocommerce_variation_is_purchasable', 'wwpp_disable_cart_lowstock', 10, 2 );
function wwpp_disable_cart_lowstock( $purchasable, $product ) {
	global $wc_wholesale_prices_premium;
  	$user_wholesale_role = $wc_wholesale_prices_premium->wwpp_wholesale_roles->getUserWholesaleRole();
  
    if( !empty( $user_wholesale_role ) ) {
		if ( wwpp_is_product_low_stock($product) ) {
			return false;
		}
	}
   return $purchasable;
}
// Disable 'Read More' button
add_filter('woocommerce_loop_add_to_cart_link', 'wwpp_lowstock_disable_read_more_button',10,2);
function wwpp_lowstock_disable_read_more_button( $add_to_cart_html, $product ) {
    global $wc_wholesale_prices_premium;
  	$user_wholesale_role = $wc_wholesale_prices_premium->wwpp_wholesale_roles->getUserWholesaleRole();
  
    if( !empty( $user_wholesale_role ) ) {
        if ( wwpp_is_product_low_stock($product) ) { 
            return '';
        }
    }
    return $add_to_cart_html;
}
// Display a message for low stock product
add_action('woocommerce_single_product_summary', 'wwpp_disable_cart_lowstock_message', 10);
add_action('woocommerce_after_shop_loop_item', 'wwpp_disable_cart_lowstock_message', 10);
function wwpp_disable_cart_lowstock_message(){
    global $product,$wc_wholesale_prices_premium;
  	$user_wholesale_role = $wc_wholesale_prices_premium->wwpp_wholesale_roles->getUserWholesaleRole();
    if( !empty( $user_wholesale_role ) ) {
        if ( wwpp_is_product_low_stock($product) ) { 
            // Feel free to change the message below if the product is low on stock
            echo __('Product is not available for wholesale customer at the moment.<br>Contact us for more information.');
        }
    }
}
// Function to check if the product is low on stock
function wwpp_is_product_low_stock($product){
    $stock_manage_stock = $product->get_manage_stock();
    $stock_quantity = $product->get_stock_quantity();
    // If the low stock treshold doen't set in the product setting, then use the woo setting in WooCommerce > Product > Inventory
    $low_stock_threshold = $product->get_low_stock_amount() ? $product->get_low_stock_amount() : get_option( 'woocommerce_notify_low_stock_amount', 2 ) ;
    // Check if manage stock is enabled on the product setting, then check if it's low on stock
    if ($stock_manage_stock && $stock_quantity <= $low_stock_threshold ) { 
        return true;
    }
    return false;
}

Comments

Add a Comment