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

Display custom stock quantity conditionally via shortcode on Woocommerce

我正在使用 惊人的答案代码,可以在任何页面或 post 通过简码显示 WooCommerce 产品的产品数量。

我只想显示最多 5 种库存产品的确切数量,并且 "More than 5" 表示 6 种或更多的数量。

修改这段代码可以吗?

您可以尝试添加到这一行

if( $stock_quantity > 0 ) return $stock_quantity;

尝试:

$overQty = "More than 5";

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

它应该有效

以下应该可以解决问题:

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

代码进入您的活动子主题(或活动主题)的 function.php 文件。它应该有效。


添加 - 也显示零库存数量:

只需更改以下代码行:

if( $stock_quantity > 0 && $stock_quantity <= 5 ) 

至:

if( $stock_quantity >= 0 && $stock_quantity <= 5 )

现在也会显示零库存…


原回答: