WooCommerce: Stock Quantity in a Shortcode

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        businessbloomer.com/woocommerce-customization
 * @author        Rodolfo Melogli, Business Bloomer
 * @compatible    WooCommerce 7
 * @community     https://businessbloomer.com/club/
 */

add_shortcode( 'stock_quantity', 'bbloomer_stock_quantity_by_product_id' );

function bbloomer_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();
}

Where to add custom code?

You should place custom PHP in functions.php and custom CSS in style.css of your child theme: where to place WooCommerce customization?

This code still works, unless you report otherwise. To exclude conflicts, temporarily switch to the Storefront theme, disable all plugins except WooCommerce, and test the snippet again: WooCommerce troubleshooting 101

Related content

Rodolfo Melogli

Business Bloomer Founder

Author, WooCommerce expert and WordCamp speaker, Rodolfo has worked as an independent WooCommerce freelancer since 2011. His goal is to help entrepreneurs and developers overcome their WooCommerce nightmares. Rodolfo loves travelling, chasing tennis & soccer balls and, of course, wood fired oven pizza. Follow @rmelogli

Questions? Feedback? Customization? Leave your comment now!
_____

If you are writing code, please wrap it like so: [php]code_here[/php]. Failure to complying with this, as well as going off topic or not using the English language will result in comment disapproval. You should expect a reply in about 2 weeks - this is a popular blog but I need to get paid work done first. Please consider joining the Business Bloomer Club to get quick WooCommerce support. Thank you!

Your email address will not be published. Required fields are marked *