【问题标题】:Displayed stock status on WooCommerce custom product type在 WooCommerce 自定义产品类型上显示库存状态
【发布时间】:2019-08-08 17:46:52
【问题描述】:

我创建了名为“事件”的自定义产品类型。在产品页面上,我想显示自定义库存状态,所以我使用以下代码:

add_action( 'woocommerce_before_add_to_cart_form', 'yy',  15 );
function yy() {
  global $post;
    if( function_exists('get_product') ){
      $product = get_product( $post->ID );
        if( $product->is_type( 'event' ) ){
          if ( $product->stock ) { // if manage stock is enabled 
            if ( number_format( $product->stock,0,'','' ) > 0 ) { // if stock is low
              echo '<p class="stock in-stock">' . number_format($product->stock,0,'','') . ' in stock</p>';
              } elseif ( number_format( $product->stock,0,'','' ) == 0 ) {
              echo '<p class="stock out-of-stock">' . __('Out of stock', 'behold-basic') . '</p>'; 
              }
        }
    };
  }
}

但是当库存为 0 时没有任何显示,应该是“缺货”。问题可能出在哪里?

【问题讨论】:

    标签: php wordpress woocommerce hook-woocommerce stock


    【解决方案1】:

    自 WooCommerce 3 以来,您的代码已经完全过时了……现在您应该尝试使用与库存相关的 WC_Product methods 而不是 (如果您的自定义产品类型扩展了 WC_Product 应该是的类)

    add_action( 'woocommerce_before_add_to_cart_form', 'before_add_to_cart_form_callback',  15 );
    function before_add_to_cart_form_callback() {
        global $product;
    
        if( $product->is_type( 'event' ) ){
            if ( $product->get_manage_stock() ) { // if manage stock is enabled
                $stock  = (int) $product->get_stock_quantity();
                $status = $product->get_stock_status();
    
                if ( $stock > 0 ) { // if stock is low
                    echo '<p class="stock in-stock">' . $stock . ' ' . __('in stock', 'behold-basic') ; '</p>';
                } elseif ( $stock == 0 ) {
                    echo '<p class="stock out-of-stock">' . __('Out of stock', 'behold-basic') . '</p>'; 
                }
            }
        }
    }
    

    它应该更好地工作......

    【讨论】:

    • 太好了,工作!是的,我的自定义产品类型扩展了 WC_Product。非常感谢!
    • @Damian 一个疏忽:我在elseif 条件下做了一点更新……
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-08
    • 1970-01-01
    • 2019-06-15
    • 1970-01-01
    • 1970-01-01
    • 2014-06-18
    • 1970-01-01
    相关资源
    最近更新 更多