Snippets / PHP
PHP
HTML
Show Quantity of Stock on Front End
D
Donald McGuinn
·
145 views
·
Updated 1 year ago
Snippet will allow you to show how much stock the item has on the front end. Works for simple products, not tested with variable or booking.
function display_product_stock() {
global $post;
// Retrieve the meta value for 'product'
$product_meta = get_post_meta($post->ID, 'product', true);
// Decode the JSON stored in the meta value
$product_data = json_decode($product_meta, true);
// Check if the product data has stock information and the stock quantity is greater than 0
if (isset($product_data['stock']['quantity']) && $product_data['stock']['quantity'] > 0) {
$stock_quantity = $product_data['stock']['quantity'];
// Display the quantity and 'in stock' text
return $stock_quantity . ' in stock';
} else {
// Handle no stock or stock not enabled
return 'Out of stock';
}
}
// Register the shortcode with WordPress
add_shortcode('product_stock', 'display_product_stock');
PHP · 21 lines
[product_stock]
HTML · 1 lines