Skip to content

Snippets / PHP

PHP

Stock Count Via Shortcode

C Creativepixels · 127 views · Updated 2 years ago
Display stock count via shortcode anywhere on your site
 
Add snippet to your functions PHP User Shortcode: [check_stock_availability] To change the print out put you modify these lines; return "Stock Quantity: {$quantity}";} else {return "Stock information not available.";
function check_stock_availability_shortcode() {
global $post, $wpdb;

// Check if the post is available
if (!$post) {
error_log("Post not found.");
return "Post not found.";
}

// Get the post ID
$post_id = $post->ID;

// Query to fetch the stock information
$query = $wpdb->prepare("
SELECT meta_value 
FROM {$wpdb->postmeta} 
WHERE post_id = %d 
AND meta_key = 'product'
", $post_id);

// Execute the query
$stock_data = $wpdb->get_var($query);

// Check if stock data exists
if (!$stock_data) {
error_log("Stock data not found for post ID: $post_id");
return "Stock data not found.";
}

// Parse the stock data (assuming it's in JSON format)
$stock_info = json_decode($stock_data, true);

// Check if stock is enabled
if (isset($stock_info['stock']['enabled']) && $stock_info['stock']['enabled']) {
// Get the quantity
$quantity = isset($stock_info['stock']['quantity']) ? $stock_info['stock']['quantity'] : 0;

return "Stock Quantity: {$quantity}";
} else {
return "Stock information not available.";
}
}

// Register the shortcode
add_shortcode('check_stock_availability', 'check_stock_availability_shortcode');
PHP · 45 lines

Discussion

Ask a question or share how you used this.

Log in to join the discussion.

No comments yet — be the first.

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.