1

我正在尝试在 WoCommerce 页面之外的普通 WordPress 页面或帖子中显示给定产品 ID 的产品数量。

我假设您将一些代码粘贴到 functions.php 中,然后在帖子或页面中放置一个片段。
我在这里真的很挣扎,到目前为止我只找到了半生不熟的答案,其中没有一个对我有用......

如何在普通的 Wordpress 页面或帖子上回显 WooCommerce 产品 ID 的库存数量?

4

1 回答 1

8

最好的方法是制作一个自定义短代码功能,即输出给定产品 ID 的产品数量。

此简码函数的代码:

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' );

}

代码在您的活动子主题(或主题)的 function.php 文件中或任何插件文件中。


用法

短代码与ID参数(目标产品 ID)一起使用。

1)在 WordPress 页面或帖子内容中,只需将此短代码粘贴到文本编辑器中即可显示给定产品 ID 的库存数量(此处 ID 为37):

[product_qty id="37"]

2 在任何 PHP 代码(示例)中:

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

3 在 HTML/PHP 页面中(示例):

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

类似: 通过 Woocommerce 上的简码有条件地显示自定义库存数量

于 2017-06-22T02:20:10.583 回答