// Add this to your theme's functions.php or use a code snippets plugin
add_action('wp_head', 'stock_status_toggle_css');
function stock_status_toggle_css() {
// Only run on single product pages
if (!is_product()) {
return;
}
// Get the product object properly
$product = wc_get_product(get_the_ID());
// Check if product exists
if (!$product) {
return;
}
// Get stock status
$is_in_stock = $product->is_in_stock();
?>
<style>
/* Hide both headings by default */
.stockin,
.stockout {
display: none !important;
}
<?php if ($is_in_stock): ?>
/* Show "In Stock" heading if product is in stock */
.stockin {
display: block !important;
}
<?php else: ?>
/* Show "Out of Stock" heading if product is out of stock */
.stockout {
display: block !important;
}
<?php endif; ?>
</style>
<?php
}
// Alternative method using body class (more flexible)
add_filter('body_class', 'add_stock_status_body_class');
function add_stock_status_body_class($classes) {
if (is_product()) {
// Get the product object properly
$product = wc_get_product(get_the_ID());
if ($product && $product->is_in_stock()) {
$classes[] = 'product-in-stock';
} else {
$classes[] = 'product-out-of-stock';
}
}
return $classes;
}