Home » WooCommerce: Stock Quantity in a Shortcode

WooCommerce: Stock Quantity in a Shortcode

by Tutor Aspire

It’s great that WooCommerce products clearly display their stock status and quantity on the single product page (and on the shop page, with this simple customization).

However, WooCommerce store owners often need to display the stock quantity in other sections of the website, such as the homepage, a blog post, a custom pricing table, and keep the quantity dynamic so that the text changes when there is a stock change.

We can therefore build a simple shortcode, that can automatically update the output, so that you never need to worry about changing that piece of content ever again. Enjoy!

With this simple snippet, you can use the shortcode you see in the screenshot to get the stock quantity for a given product ID.

PHP Snippet: Display Stock Quantity for a Product ID Via Shortcode

/**
 * @snippet       Stock Quantity Shortcode
 * @how-to        Get tutoraspire.com FREE
 * @author        Tutor Aspire
 * @compatible    WooCommerce 7
 * @donate $9     https://www.tutoraspire.com
 */

add_shortcode( 'stock_quantity', 'tutoraspire_stock_quantity_by_product_id' );

function tutoraspire_stock_quantity_by_product_id( $atts ) {
$product_id = $atts['id'] ? $atts['id'] : 0;
$product = wc_get_product( $product_id );
if ( ! $product || ( $product && ! $product->managing_stock() ) ) return;
return $product->get_stock_quantity();
}

You may also like