"Out of Stock" Labels in Variation Dropdowns
Adds "(out of stock)" next to sold-out options in the variation dropdown of single-attribute products, such as sizes, so shoppers see availability before choosing.
Opens WPIDE on
Code
$wpide_oos_label = 'out of stock'; // Text added to sold-out options.
add_filter( 'woocommerce_variation_option_name', function ( $name, $term = null, $attribute = '', $product = null ) use ( $wpide_oos_label ) {
static $map = array();
if ( ! $product instanceof WC_Product_Variable || ! $attribute ) {
return $name;
}
$id = $product->get_id();
if ( ! isset( $map[ $id ] ) ) {
$map[ $id ] = false;
$variation_attributes = $product->get_variation_attributes();
if ( 1 === count( $variation_attributes ) ) {
$map[ $id ] = array();
foreach ( $product->get_children() as $child_id ) {
$child = wc_get_product( $child_id );
if ( $child ) {
foreach ( $child->get_attributes() as $value ) {
$map[ $id ][ strtolower( (string) $value ) ] = $child->is_in_stock();
}
}
}
}
}
if ( ! is_array( $map[ $id ] ) ) {
return $name;
}
$key = strtolower( $term instanceof WP_Term ? $term->slug : (string) $name );
return ( isset( $map[ $id ][ $key ] ) && ! $map[ $id ][ $key ] ) ? $name . ' (' . $wpide_oos_label . ')' : $name;
}, 10, 4 );
Notes
Applies to products whose variations use one attribute; products with several attributes are left unchanged.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.