Display sold out on WooCommerce variable product when all variations are out of stock Display sold out on WooCommerce variable product when all variations are out of stock wordpress wordpress

Display sold out on WooCommerce variable product when all variations are out of stock


You can create a custom conditional function to check if all variations of a variable product are "out of stock" as follows:

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() ) {            $children_count++; // count out of stock children        }    }    // Compare counts and return a boolean    return count($variation_ids) == $children_count ? true : false;}

Then you will use it in your revisited hooked function below:

add_action( 'woocommerce_before_shop_loop_item_title', 'display_products_loop_out_of_stock' ); function display_products_loop_out_of_stock() {    global $product;    if ( ( ! $product->is_type('variable') && ! $product->is_in_stock()  )     || ( $product->is_type('variable') && is_variable_product_out_of_stock( $product ) ) ) {        echo '<span class="soldout">Sold Out</span>';    }} 

Code goes in functions.php file of the active child theme (or active theme). It should works.


I made a lighter version of @LoicTheAztec 's function that will stop looping as soon as it finds a variable that is in stock:

function is_variable_product_out_of_stock($product) {    $variation_ids = $product->get_visible_children();    foreach($variation_ids as $variation_id) {        $variation = wc_get_product($variation_id);        if ($variation->is_in_stock())            return false;    }    return true;}

Also with no fatal error because he made two critical typos in his function.

You can the do something custom like he did:

add_action('woocommerce_before_shop_loop_item_title', 'display_products_loop_out_of_stock');function display_products_loop_out_of_stock() {    global $product;    if ((!$product->is_type('variable') and !$product->is_in_stock()) or ($product->is_type('variable') and is_variable_product_out_of_stock($product)))        echo '<span class="soldout">Sold Out</span>';}