The following should do the trick:
if( !function_exists('show_specific_product_quantity') ) {
function show_specific_product_quantity( $atts ) {
// Shortcode Attributes
$atts = shortcode_atts(
array(
'id' => '', // Product ID argument
),
$atts,
'product_qty'
);
if( empty($atts['id'])) return;
$stock_quantity = 0;
$product_obj = wc_get_product( intval( $atts['id'] ) );
$stock_quantity = $product_obj->get_stock_quantity();
if( $stock_quantity > 0 && $stock_quantity <= 5 )
return $stock_quantity;
elseif( $stock_quantity > 5 )
return __("More than 5", "woocommerce");
}
add_shortcode( 'product_qty', 'show_specific_product_quantity' );
}
Code goes in function.php file of your active child theme (or active theme). It should work.
Addition - Display Zero Stock number too:
Just change the following code line:
if( $stock_quantity > 0 && $stock_quantity <= 5 )
to:
if( $stock_quantity >= 0 && $stock_quantity <= 5 )
Now zero stock will be displayed too…
Original answer: WooCommerce: Display stock quantity for a given product ID on normal Pages or Posts
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…