【问题标题】:Display product stock status on single product pages in WooCommerce when price field is empty当价格字段为空时,在 WooCommerce 中的单个产品页面上显示产品库存状态
【发布时间】:2021-04-22 11:39:36
【问题描述】:

我正在 WooCommerce 产品中添加新的库存状态。已经在How to add custom stock status to products in WooCommerce 4+答案码的帮助下完成了。

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

如果价格字段为空,我该怎么做才能显示状态?

【问题讨论】:

  • 您应该问自己的第一个问题是。如果您不使用该额外代码,则会显示产品的默认产品库存状态。 如果价格为空,是否仍显示默认产品库存状态? 如果没有,那么这与额外代码无关,而是与 WooCommerce 中的标准行为有关,因此您必须查找朝那个方向的解决方案
  • @7uc1f3r 它在默认状态下不显示产品的库存状态,价格为空。我能做些什么呢?

标签: php wordpress woocommerce product


【解决方案1】:

您会看到,如果价格为空,除了不显示产品库存状态外,此价格(HTML 代码)也不会显示。因为如果价格为空,该产品将被视为不可购买。

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

因此,与其专注于显示产品库存状态,不如在通常显示价格的地方显示其他内容(HTML/文本)会简单得多, 这可以通过使用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/文本不会显示在您通常看到产品库存状态的位置,而是显示在通常显示价格的位置。

【讨论】:

    猜你喜欢
    • 2019-01-09
    • 1970-01-01
    • 1970-01-01
    • 2021-11-01
    • 2019-12-04
    • 1970-01-01
    • 2017-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多