Maintain Product Quantity during Wholesale User Purchase

In the world of e-commerce, managing wholesale transactions efficiently is crucial for both sellers and buyers. WooCommerce, a popular e-commerce platform, offers various plugins to enhance its functionality. One such plugin is the Barn2 WooCommerce Wholesale Pro Plugin, which provides advanced features for wholesale users. However, an important consideration for wholesale transactions is the proper handling of product quantities. In this article, we’ll explore a solution using a custom code snippet to ensure that product quantities are replenished when a wholesale user makes a purchase.


To automatically add back product quantities for wholesale users, we can utilize a custom code snippet. This snippet hooks into the ‘woocommerce_checkout_order_processed’ action, ensuring that it runs when an order is successfully processed.

function add_quantity_back_if_wholesale( $order_id ) {
    $order = wc_get_order( $order_id );

    // Check if the Wholesale Pro Plugin is active and the user is a wholesale user
    if ( class_exists( '\Barn2\Plugin\WC_Wholesale_Pro\Util' ) && \Barn2\Plugin\WC_Wholesale_Pro\Util::is_wholesale_user( wp_get_current_user() ) ) {
        foreach ( $order->get_items() as $item ) {
            $product = $item->get_product();

            // Retrieve the quantity and stock information
            $quantity = $item->get_quantity();
            $stock_quantity = $product->get_stock_quantity();

            // Calculate the new stock quantity and update the product
            $new_stock_quantity = $stock_quantity + $quantity;
            $product->set_stock_quantity( $new_stock_quantity );
            $product->save();
        }
    }
}

// Hook the function to the 'woocommerce_checkout_order_processed' action
add_action( 'woocommerce_checkout_order_processed', 'add_quantity_back_if_wholesale' );

Explanation:
This code snippet performs the following steps:

  1. It checks if the WooCommerce Wholesale Pro Plugin is active and if the user making the purchase is a wholesale user.
  2. For each item in the order, it retrieves the associated product and calculates the new stock quantity by adding the ordered quantity.
  3. The product’s stock quantity is then updated, and the changes are saved.

By incorporating this code into the child theme’s functions.php file, WooCommerce will automatically replenish product quantities for wholesale users when their orders are processed.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top