在WooCommerce自定义产品类型上显示库存状态

时间:2019-08-08 17:46:52

标签: php wordpress woocommerce hook-woocommerce stock

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

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时,没有任何显示,应为“缺货”。问题可能在哪里?

1 个答案:

答案 0 :(得分:2)

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

应该更好地工作……