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

a 夏天 提交于 2019-12-06 15:07:59

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/44686282/woocommerce-display-stock-quantity-for-a-given-product-id-on-normal-pages-or-po

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!