Greying out "out-of-stock" product variations with custom stock quantity reduction in WooCommerce
- Compare the total stock quantity to the newly added setting
$multiplier
- Comment with explanation added to the code
function filter_woocommerce_variation_is_active( $active, $variation ) { // Get multiplier $multiplier = get_post_meta( $variation->get_variation_id(), '_stock_multiplier', true ); // NOT empty if ( ! empty( $multiplier ) ) { // Get stock quantity $var_stock_count = $variation->get_stock_quantity(); // Stock quantity < multiplier if( $var_stock_count < $multiplier ) { $active = false; } } return $active;}add_filter( 'woocommerce_variation_is_active', 'filter_woocommerce_variation_is_active', 10, 2 );
It doesn't work because:
$item
variable is not defined in your code.- your custom field is defined in the parent variable product.
So you need to replace:
$multiplier = $item->get_product()->get_meta( '_stock_multiplier' );
by the folling (getting the data from the parent variable product):
$multiplier = get_post_meta( $variation->get_parent_id(), '_stock_multiplier', true );
So in your code:
add_filter( 'woocommerce_variation_is_active', 'my_jazzy_function', 10, 2 ); function my_jazzy_function( $active, $variation ) { // Get multiplier if( $multiplier = get_post_meta( $variation->get_parent_id(), '_stock_multiplier', true ) { // Get stock quantity $var_stock_count = (int) $variation->get_stock_quantity(); // if there are 5 or less, disable the variant, could always just set to 0 return $var_stock_count <= $multiplier ? false : $active; } return $active;}
It should work now.