当价格字段为空时在 WooCommerce 的单个产品页面上显示产品库存状态

Display product stock status on single product pages in WooCommerce when price field is empty

我要在 WooCommerce 产品中添加新的库存状态。这是在 答案代码的帮助下完成的。

但问题是,当产品的价格字段为空时,它不显示状态(前端)。但除此之外,当产品有价格时,它会显示状态。

我该怎么做才能在价格字段为空的情况下显示状态?

你会看到,如果价格为空,除了不显示商品库存状态外,也不会显示该商品的价格(HTML代码)。因为如果价格为空则视为不可购买。

所以为了显示产品库存状态,如果价格为空,您应该使产品可购买。但是,我不相信这是你的意图?

因此,与其专注于显示产品库存状态,不如在正常显示价格的地方显示其他内容 (HTML/text) 会简单得多, 这可以通过使用 woocommerce_empty_price_html 过滤器挂钩

来完成
  1. 所以要么你放弃产品库存状态的整个想法并简单地使用:
function filter_woocommerce_empty_price_html( $html, $product ) {
    // NOT true on a single product page, RETURN
    if ( ! is_product() ) return $html;
    
    // Add HTML
    $html = '<p>My text</p>';

    return $html;
}
add_filter( 'woocommerce_empty_price_html', 'filter_woocommerce_empty_price_html', 10, 2 );

  1. 或者您进一步了解产品库存状态,并在此基础上获得:
function filter_woocommerce_empty_price_html( $html, $product ) {
    // NOT true on a single product page, RETURN
    if ( ! is_product() ) return $html;
    
    // Get stock status
    $product_stock_status = $product->get_stock_status();
    
    // Compare
    if ( $product_stock_status == 'MY CUSTOM STATUS' ) {
        // Add HTML
        $html = '<p>My text based on product stock status</p>';
    }

    return $html;
}
add_filter( 'woocommerce_empty_price_html', 'filter_woocommerce_empty_price_html', 10, 2 );

此解决方案的唯一缺点是您的新 HTML/text 不会显示在您通常看到产品库存状态的位置,而是显示价格的位置。