The below WooCommerce function is a custom function that adds a notice to the product page when backorders are allowed and the product is out of stock.
Here's an explanation of how it works:
-
The function custom_notice_for_backorders_allowed() is defined and hooked to the woocommerce_after_add_to_cart_form action using the add_action() function. This action hook is triggered after the add to cart form is displayed on the product page.
-
Inside the function, the global $product object is instantiated, representing the current product being displayed.
-
The function checks if backorders are allowed for the product using the $product->backorders_allowed() method. If backorders are allowed and the product's stock quantity is less than or equal to 0 (out of stock), the condition is met.
-
Within the condition, a red-colored and bold "Orders only!" notice is displayed using HTML markup and inline styles.
To insert this function into the functions.php file of your WordPress theme, follow these steps:
- Open the functions.php file of your theme or preferably your child theme. Typically, it is located in the root folder of your active theme or child theme.
- Add the following code at the end of the file:
// www.websitefunctions.comadd_action( 'woocommerce_after_add_to_cart_form', 'custom_notice_for_backorders_allowed' );
function custom_notice_for_backorders_allowed()
{
//instantinate product object
global $product;
//check if backorders are allowed
if ($product->backorders_allowed() && $product->get_stock_quantity() <= 0)
{
?>
<span style="color: red; font-weight: 700; font-size: 22px; ">Orders only!</span>
<?php
}
}
- Save the changes to the functions.php file.
- Once you have inserted this code into the functions.php file, the custom notice will be displayed on the product page whenever backorders are allowed and the product is out of stock.