Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
479 views
in Technique[技术] by (71.8m points)

php - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...