The custom code in this download folder displays a Low Stock Banner over the product image on shop page archives.
Installation
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:
add_low_stock_banner_to_archive
function :
- This function is hooked into the w
oocommerce_before_shop_loop_item_title
action, 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
$product->get_stock_quantity()
method. - It then retrieves the low stock threshold value from a custom field
_low_stock_threshold
usingget_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
div
element with the classlow-stock-banner
containing the text “Low Stock”.
add_low_stock_banner_styles
function :This function is hooked into
wp_head
and 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.
Leave a Reply