Alex
Alex

Reputation: 1497

Display custom stock quantity conditionally via shortcode on Woocommerce

I'm using WooCommerce: Display stock quantity for a given product ID on normal Pages or Posts amazing answer code that works to display the product quantity for a WooCommerce product in any page or post via a shortcode.

I would like to only display the exact quantity up to 5 products in stock and have "More than 5" for any quantity of 6 or more.

Can it be done by modifying this code?

Upvotes: 2

Views: 1649

Answers (2)

LoicTheAztec
LoicTheAztec

Reputation: 253901

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

Upvotes: 3

Cory Spinney
Cory Spinney

Reputation: 1

You could try adding to this line

if( $stock_quantity > 0 ) return $stock_quantity;

try:

$overQty = "More than 5";

if( $stock_quantity > 5 ){ return $overQty } else { return $stock_quantity };

it should work

Upvotes: -2

Related Questions