WooCommerce: Display stock quantity for a given product ID on normal Pages or Posts

Nathan Winch picture Nathan Winch · Jun 21, 2017 · Viewed 9.7k times · Source

I am trying to display the product quantity for a given product ID outside WoCommerce pages, in the normal WordPress Pages or Posts.

I assume you paste some code into functions.php then have a snippet you put in the post or page.
I'm really struggling here and only half-baked answers I've found so far where none of them work for me...

How do I echo the stock quantity of a WooCommerce product ID on a normal Wordpress page or post?

Answer

LoicTheAztec picture LoicTheAztec · Jun 22, 2017

The best way is to make a custom shortcode function, that is going to output the product quantity for a given product ID.

The code for this shortcode function:

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 ) return $stock_quantity;

    }

    add_shortcode( 'product_qty', 'show_specific_product_quantity' );

}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.


USAGE

The shortcode works with an ID argument (the targeted product ID).

1) In a WordPress Page or Post content, just paste this shortcode in the text editor to display the stock quantity for a given product ID (Here the ID is 37):

[product_qty id="37"]

2 In any PHP code (example):

echo '<p>Product quantity is: ' . do_shortcode( '[product_qty id="37"]' ) .'</p><br>';

3 In an HTML/PHP page (example):

<p>Product quantity is: <?php echo do_shortcode( '[product_qty id="37"]' ); ?></p>

Similar: Display custom stock quantity conditionally via shortcode on Woocommerce