Home > Software engineering >  WooCommerce Offset Stock levels Based On Custom Field Value Threshold
WooCommerce Offset Stock levels Based On Custom Field Value Threshold

Time:12-19

I need to set a threshold on a per product basis for stock inventory.

Example : If the product has a threshold of 10 and there's 10 or less in stock, the product shows the out of stock text. If the threshold is set at 10 but there's 15 in stock, 5 is shown in stock.

So what i need to do is offset the real inventory levels on a per product basis using a value.

This is the code i'm trying to get working

add_filter( 'woocommerce_get_availability', 'override_get_availability', 10, 2);
function override_get_availability( $availability, $product ) {

$stock_threshold = get_post_meta( $product->get_id(), '_stock_threshold', true );

if ( $product->managing_stock() && ! empty( $stock_threshold ) ) {

$availability['availability'] = $product->get_stock_quantity() - $stock_threshold;

return $availability;

    }

}

This code doesn't show the Out of Stock text on the single product page if the inventory is calculated at 0 or less than zero.

Example : When the stock level is set at 2 and the offset is set at 2, it = 0 so should show Out of Stock but doesn't.

CodePudding user response:

Your current code seems to be correctly offsetting the stock quantity by the threshold value. However, it does not seem to be taking into account whether the resulting stock quantity is zero or less.

To fix this, you can add an additional check to see if the resulting stock quantity is less than or equal to zero, and if it is, set the availability message to "Out of stock". Here's how you can do that:

` add_filter( 'woocommerce_get_availability', 'override_get_availability', 10, 2); function override_get_availability( $availability, $product ) { $stock_threshold = get_post_meta( $product->get_id(), '_stock_threshold', true );

if ( $product->managing_stock() && ! empty( $stock_threshold ) ) {
    $new_stock_quantity = $product->get_stock_quantity() - $stock_threshold;

    if ($new_stock_quantity <= 0) {
        // Set availability to "Out of stock" if the resulting stock quantity is zero or less
        $availability['availability'] = __( 'Out of stock', 'woocommerce' );
    } else {
        // Set availability to the new stock quantity
        $availability['availability'] = $new_stock_quantity;
    }

    return $availability;
}

} `

This should display the "Out of stock" message if the resulting stock quantity is zero or less, and the actual stock quantity minus the threshold value if the resulting stock quantity is greater than zero.

  • Related