使用woocommerce_get_availability hook时的几个问题

Several issues when using woocommerce_get_availability hook

我正在尝试在缺货产品的单个产品页面上显示 'out of stock message'。

我的 functions.php

中有此代码
function stock_catalog() {
    global $product;
    if (number_format($product->stock, 0, '', '') <= 0) {
        echo '<p class="mb-2"> ' . __('** Sorry currently out of stock **', 'text- 
   domain') . '</p>';
    }
}
add_action('woocommerce_get_availability', 'stock_catalog');

我收到以下错误:

注意:股票被错误调用。不应直接访问产品属性。回溯:require('wp-blog-header.php'), require_once('wp-includes/template-loader.php'), include('/plugins/woocommerce/templates/single-product.php'), wc_get_template_part, load_template, require('/themes/mytheme/woocommerce/content-single-product.php'), do_action('woocommerce_single_product_summary'), WP_Hook->do_action, WP_Hook- >apply_filters, woocommerce_template_single_add_to_cart, do_action('woocommerce_simple_add_to_cart'), WP_Hook->do_action, WP_Hook->apply_filters, woocommerce_simple_add_to_cart, wc_get_template, include('/plugins/woocommerce/templates/single-product/add-to-cart/simple.php'), wc_get_stock_html, WC_Product->get_availability, apply_filters('woocommerce_get_availability'), WP_Hook->apply_filters, stock_catalog, WC_Abstract_Legacy_Product->__get, wc_doing_it_wrong 请参阅第 5313 行 /homepages/17/d825330075/htdocs/mytheme/wp-includes/functions.php 中的“在 WordPress 中调试”以获取更多信息

有解决此问题的想法吗?

需要使用方法“get_stock_quantity”


function stock_catalog($availability, $product) {

    if ( $product->managing_stock() && $product->get_stock_quantity() <= 0) {
        $availability['availability'] = __('** Sorry currently out of stock **', 'text- 
   domain');
    }

    return $availability;
}
add_filter('woocommerce_get_availability', 'stock_catalog', 10, 2);

更多详情https://woocommerce.github.io/code-reference/classes/WC-Product.html#method_get_stock_quantity

您的代码包含的不是 1 个错误,而是多个错误

  • woocommerce_get_availability 不是一个动作,而是一个过滤器钩子
  • number_format() 在这里完全不适用
  • $product->stock 需要替换为 $product->get_stock_quantity()
  • managing_stock()必须为真,否则不可能set/store一个产品库存数量
  • 回声不适用于过滤器挂钩,应使用return
  • 输出应分配给$availability
  • $product 作为参数传递给函数,所以不需要使用全局变量

所以你得到:

// Change stock text
function filter_woocommerce_get_availability( $availability, $product ) {       
    // Managing stock is activated
    if ( $product->managing_stock() ) {
        // Stock quantity
        $stock_quantity = $product->get_stock_quantity();
        
        // Stock quantity is less than or equal to 0
        if ( $stock_quantity <= 0 ) {
            $availability['availability'] = __( 'Sorry currently out of stock', 'woocommerce' );
        }
    }

    return $availability;
}
add_filter( 'woocommerce_get_availability', 'filter_woocommerce_get_availability', 10, 2 );