PHP Code SnippetAfter installing a child theme, navigate to Appearance > Theme Editor > functions.php and paste at the bottom of the input.
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');