I've got a button that should appear depending upon whether or not a product or one of its variations (if it's a variable product) is out of stock. If it's in stock, don't display it.
Been playing with lots of scripts but nothing seems to stick. Here's where I am currently at:
Example: https://bplsource.com/product/techniglove-12%e2%80%b3-nitrile-usp-797-white-powder-free/
HTML:
<div class=\"woocommerce-variation-add-to-cart variations_button\">\n\t<p class=\"stock out-of-stock\">Out of stock, Can be backordered<\/p>
PHP with JavaScript:
// Add Custom Content Before 'Add To Cart' Button On Product Page
function my_content() {
global $product;
// Check if the product or any of its variations is out of stock
$is_out_of_stock = false;
if ($product->get_manage_stock() && $product->get_stock_quantity() <= 0) {
$is_out_of_stock = true;
}
if ($product->is_type('variable') && !$is_out_of_stock) {
foreach ($product->get_children() as $variation_id) {
$variation = wc_get_product($variation_id);
if ($variation && $variation->get_manage_stock() && $variation->get_stock_quantity() <= 0) {
$is_out_of_stock = true;
break;
}
}
}
// Display the out-of-stock message if needed
if ($is_out_of_stock) {
echo '<p class="stock out-of-stock">Out of stock, Can be backordered</p>';
}
// Enqueue JavaScript to dynamically show or hide the out-of-stock message
?>
<script>
jQuery(function($) {
var isOutOfStock = <?php echo $is_out_of_stock ? 'true' : 'false'; ?>;
if (!isOutOfStock) {
$('.stock.out-of-stock').hide();
}
});
</script>
<?php
}
// Add the action hook only once
add_action('woocommerce_before_add_to_cart_button', 'my_content');
Solution 1:-
You can simply use CSS for this.
This CSS rule will hide the "Out of stock, Can be backordered" if the Add to Cart Button is Disabled.
Solution 2:-
The JavaScript that you are "enqueuing" directly, is being added to DOM AFTER the "Ready" event is triggered. So your function will never run as it is listening for the ready trigger.
Instead, you need to update the script as follows:-