Skip to content

Snippets / PHP

PHP

Remodified version of stock availability

E ejahid14 · 79 views · Updated 1 year ago
Stock > 10 → Shows "Available" in green.Stock between 1-10 → Shows "Almost Sold Out" in orange.Stock = 0 or not set → Shows "Sold Out" in red.
Now, when you use [product_stock] in your WordPress post/page, it will display the appropriate message based on stock levels.
Go to appearance->theme edit->voxel-child->function.php 
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 stock information exists
if (isset($product_data['stock']['quantity'])) {
$stock_quantity = (int) $product_data['stock']['quantity'];

// Define stock levels
if ($stock_quantity > 10) {
return "<span style='color: green; font-weight: bold;'>Available ($stock_quantity in stock)</span>";
} elseif ($stock_quantity > 0 && $stock_quantity <= 10) {
return "<span style='color: orange; font-weight: bold;'>Almost Sold Out ($stock_quantity left)</span>";
} else {
return "<span style='color: red; font-weight: bold;'>Sold Out</span>";
}
} else {
return "<span style='color: red; font-weight: bold;'>Sold Out</span>";
}
}

// Register the shortcode with WordPress
add_shortcode('product_stock', 'display_product_stock');
PHP · 27 lines

Discussion 1

Ask a question or share how you used this.

Log in to join the discussion.
Donald McGuinn 1 year ago

With 1.5.5 you actually don’t need any code to show stock and can use dynamic tags and visibility to do the above too.

Voxel Guide assistant
Ask about snippets, addons & how-tos

Hey — how can I help?

I can dig through the library for snippets, addons, and tutorials.

AI can be wrong — double-check anything important.