通过 Woocommerce 上的短代码有条件地显示自定义库存数量 [英] Display custom stock quantity conditionally via shortcode on Woocommerce

查看:63
本文介绍了通过 Woocommerce 上的短代码有条件地显示自定义库存数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 WooCommerce:在普通页面或帖子上显示给定产品 ID 的库存数量 惊人的答案代码,可用于在任何页面或通过短代码发布的帖子中显示 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.

我只想显示最多 5 件库存产品的确切数量,并且超过 5 件"表示任何 6 件或更多的数量.

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?

推荐答案

以下应该可以解决问题:

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

代码位于活动子主题(或活动主题)的 function.php 文件中.它应该可以工作.

Code goes in function.php file of your active child theme (or active theme). It should work.

添加 - 也显示零库存编号:

只需更改以下代码行:

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

到:

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

现在也将显示零库存......

Now zero stock will be displayed too…

原答案:WooCommerce:在普通页面或帖子上显示给定产品 ID 的库存数量

这篇关于通过 Woocommerce 上的短代码有条件地显示自定义库存数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆