WooCommerce: show outofstock based on stock and backorders conditions

i want to know how to show out of stock label and hide add to cart, based on backorders and stock quantity. I writed code that worked well for simple product, but need help to do it for variations.
Code is:

// Custom conditional fuction to target specific user roles
function is_allowed_user_role() {
    $targeted_roles = array( 'administrator' ); // Here define your targeted user roles
    return (bool) array_intersect( wp_get_current_user()->roles, $targeted_roles );
}

function is_variable_product_out_of_stock( $product ) {
    $children_count = 0; // initializing
    $variation_ids  = $product->get_visible_children();
        
    // Loop through children variations of the parent variable product
    foreach( $variation_ids as $variation_id ) {
        $variation = wc_get_product($_variation_id); // Get the product variation Object
            
        if( ! $variation->is_in_stock() && $variation->get_stock_quantity() <= 0 ) {
            $children_count++; // count out of stock children
        }
    }
    // Compare counts and return a boolean
    return count($variation_ids) == $children_count ? true : false;
}

/* get custom stock status */
function get_custom_stock_status( $data, $product ) {
    
    if ( $product->is_type('simple')) {
        if ( $product->get_stock_quantity() <= 0 && !is_allowed_user_role() && $product->get_backorders() == 'no') {
            $data = array(  'availability' => __( 'Out of Stock', 'woocommerce' ), 'class' => 'out-of-stock'  );
            echo "<style> form.cart { display:none; } </style>";    
    }
        elseif ( !is_allowed_user_role() && $product->get_backorders() == 'yes' && $product->get_stock_quantity() <= 0) {
            $data = array(  'availability' => __( 'In Stock', 'woocommerce' ), 'class' => 'in-stock'  );
        }
    }   
    elseif( $product->is_type('variable') && is_variable_product_out_of_stock( $product )) {
        $data = array(  'availability' => __( 'Out of Stock', 'woocommerce' ), 'class' => 'out-of-stock'  );
        echo "<style> form.cart { display:none; } </style>";    
    }
    
    return $data;
}
add_action('woocommerce_get_availability', 'get_custom_stock_status', 10, 2);

How i can do same for variations?
Thanks!

Source: Ask PHP

LEAVE A COMMENT