Aug 27
Handle Out-of-Stock Display for Variable Products in WooCommerce
When a product goes out of stock, the "Add to Cart" button should not be displayed. It would also be better if the product card becomes slightly greyed out (similar to the Flatsome theme). For simple products, this can be achieved with a single code snippet—both the button is removed, and the card turns grey.
However, the problem is that this code does not work for variable products. That is, when all variations of a variable product are out of stock, the product card does not change, and the Add to Cart button is not properly managed.
Please provide a code snippet or a solution that also works for variable products (so that when all variations are out of stock, the product card turns grey, and the Add to Cart button is removed).
<?php
if ( ! defined( 'ABSPATH' ) ) { exit; }
/**
* Helper: is simple & out of stock?
*/
function wcsog_is_simple_oos( $product ) {
return ( $product instanceof WC_Product )
&& $product->is_type( 'simple' )
&& ! $product->is_in_stock();
}
add_filter( 'woocommerce_loop_add_to_cart_link', function( $link, $product, $args ) {
if ( wcsog_is_simple_oos( $product ) ) {
return '';
}
return $link;
}, 10, 3 );
add_action( 'template_redirect', function() {
if ( is_product() ) {
$product = wc_get_product( get_the_ID() );
if ( wcsog_is_simple_oos( $product ) ) {
// Add to Cart
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
}
}
} );
add_filter( 'post_class', function( $classes, $class, $post_id ) {
$product = wc_get_product( $post_id );
if ( $product && wcsog_is_simple_oos( $product ) ) {
$classes[] = 'wcsog-simple-oos';
}
return $classes;
}, 10, 3 );
add_action( 'wp_head', function() {
?>
<style id="wcsog-style">
.wcsog-simple-oos {
filter: grayscale(100%);
opacity: 0.65;
transition: opacity .2s ease, filter .2s ease;
}
.wcsog-simple-oos:hover {
opacity: 0.65 !important;
filter: grayscale(100%) !important;
}
.wcsog-simple-oos a.button,
.wcsog-simple-oos .add_to_cart_button,
.wcsog-simple-oos .ajax_add_to_cart {
pointer-events: none;
cursor: not-allowed;
opacity: 0.6;
}
.wcsog-simple-oos .box-image img {
filter: grayscale(100%) !important;
opacity: 0.6 !important;
}
.wcsog-simple-oos .box-text {
opacity: 0.85;
}
</style>
<?php
} );
Pending