Display stock count via shortcode anywhere on your site
Â
Add snippet to your functions PHP
User Shortcode:
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');