简体   繁体   中英

Greying out product variations based on stock quantity and SKU

I have a variable product with 2 different variations. Both variations use inventory at the product level. The stock is at 3 and I have the following two variations:

  • Buy with 1 credit
  • Buy with 3 credits

The stock of the product is 3 and when someone with 3 credits buys the product, 3 is also deducted from the stock by means of a custom-written function, so that the stock becomes 0 and the product is no longer visible.

When someone buys the product with 1 credit, 1 is deducted from the stock, so that the stock becomes 2. If this happens I would like the variation "Buy with 3 credits" to become inactive or not visible anymore.

How can I check through a function when the stock is equal or less than 2 and make sure that "Buy with 3 credits" variation is no longer visible or becomes inactive? - SKU always starts with "003*****"

So if product inventory is equal or less than 2 and SKU starts with 003, then the product variation will not show.


I already got this working, how can I also check if the SKU of this variable starts with "003"?

add_filter( 'woocommerce_variation_is_active', 'grey_out_variations_out_of_stock', 10, 2 );
 
function grey_out_variations_out_of_stock( $is_active, $variation ) {
    if ( $variation->get_stock_quantity() == 2 ) return false;
    return $is_active;
}

You can use $variation->get_sku() and str_starts_with() - (PHP 8), which will check if a string starts with a certain substring.

So you get:

function filter_woocommerce_variation_is_active( $active, $variation ) {
    // Get SKU
    $sku = $variation->get_sku();

    if ( $variation->get_stock_quantity() <= 2 && str_starts_with( $sku, '003' ) ) {
        $active = false;
    }
    
    return $active;
}
add_filter( 'woocommerce_variation_is_active', 'filter_woocommerce_variation_is_active', 10, 2 );

Note: for PHP 7.0 or older you can use substr( $sku, 0, 3 ) === '003'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM