The custom code in this download folder displays a Low Stock Banner over the product image on shop page archives.
There’s only 1 step :
Copy and paste the PHP code to the end of your child themes functions file or custom functionality/code snippets plugin.
Developers : How The Code Works
Here’s a break down describing how the code works:
- This function is hooked into the w
oocommerce_before_shop_loop_item_titleaction, which is called before the title of each product on the archive page.
- It starts by getting the stock quantity of the current product using the
- It then retrieves the low stock threshold value from a custom field
get_post_meta($product->get_id(), '_low_stock_threshold', true). This value is stored in the WordPress database for each product.
- If the low stock threshold is not set
empty, it falls back to using the stock quantity as the threshold value.
- It checks if the stock quantity is less than or equal to the low stock threshold and greater than 0. If this condition is true, it means the product is low in stock.
- If the product is low in stock, it echoes a
divelement with the class
low-stock-bannercontaining the text “Low Stock”.
This function is hooked into
wp_headand adds some inline CSS styles for the low stock banner. The styles include a red background color, white text color, padding, and absolute positioning to place the banner at the top left corner of the product image.
In summary, this code dynamically checks whether a product is low in stock based on a threshold value. If a low stock threshold is set for a product, it uses that value; otherwise, it uses the stock quantity. If the product is considered low in stock, a “Low Stock” banner is displayed on the archive page near the product title. The styles for the banner are defined in the
add_low_stock_banner_styles function inline.