【问题标题】:Display custom stock quantity conditionally via shortcode on Woocommerce通过 Woocommerce 上的简码有条件地显示自定义库存数量
【发布时间】:2019-05-20 05:35:03
【问题描述】:

我正在使用 WooCommerce: Display stock quantity for a given product ID on normal Pages or Posts 惊人的答案代码,它可以在任何页面中显示 WooCommerce 产品的产品数量或通过简码发布。

我想只显示库存产品的确切数量,最多 5 件,并且对于 6 件或更多的任何数量,我都会显示“超过 5 个”。

可以通过修改这段代码来完成吗?

【问题讨论】:

    标签: php woocommerce product shortcode stock


    【解决方案1】:

    以下应该可以解决问题:

    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 )
    

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


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

    【讨论】:

      【解决方案2】:

      你可以尝试添加到这一行

      if( $stock_quantity > 0 ) return $stock_quantity;
      

      尝试:

      $overQty = "More than 5";
      
      if( $stock_quantity > 5 ){ return $overQty } else { return $stock_quantity };
      

      它应该可以工作

      【讨论】:

      • 我没有否决您的答案,但它不起作用。我得到一个空白屏幕,代码一定有问题。
      • 简单地返回一个字符串变量不会在网页上向最终用户显示任何输出
      • 你可以尝试回显它而不是返回
      • @CorySpinney 仅供参考: 在短代码功能上,数据永远不会回显,而是始终返回,就像在过滤器挂钩中一样。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-19
      • 2021-10-28
      • 2023-03-05
      • 2013-09-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多