WooCommerce如何判断商品是否有库存 解决is_in_stock报null错误
问题解决办法
报错根本原因
你遇到的报错是两个问题共同导致的:
- 全局
$product对象不可靠:部分场景下这个全局对象还未初始化,值为null,直接调用成员方法就会触发你遇到的报错 - 过滤器钩子不能直接输出内容:
woocommerce_germanized_delivery_time_html是过滤器类型钩子,要求必须返回处理后的内容,直接用echo输出会导致页面渲染逻辑异常
修复后的代码
function filter_woocommerce_germanized_delivery_time_html( $str_replace, $html ) { global $product; // 先校验商品对象是否合法 if ( ! $product instanceof WC_Product ) { return $html; } // 库存判断合法后拼接返回内容,不要直接echo if( $product->is_in_stock() ) { $custom_content = '<p class="wc-gzd-additional-info delivery-time-info">'; $custom_content .= $str_replace; $custom_content .= '</p>'; $custom_content .= '<p class="wc-gzd-additional-info"><a href="https://xyz.at/info/lieferzeiten/" target="_blank"><i class="fas fa-shipping-fast"></i> EU-Lieferzeiten</a></p></span>'; return $custom_content; } // 无库存时返回空或者原HTML,可根据需求调整 return ''; } add_filter( 'woocommerce_germanized_delivery_time_html', 'filter_woocommerce_germanized_delivery_time_html', 10, 2 );
额外说明
- 优先使用
is_in_stock()做库存判断:如果商品未启用库存管理功能,get_stock_quantity()会返回false,直接判断数值大小会出现逻辑异常,is_in_stock()已经兼容了库存管理启用/关闭的所有场景 - 如果你需要在非商品详情页的其他场景(比如商品列表页)也生效,可以进一步通过钩子传参或者循环内获取商品对象的方式优化,当前代码已经兼容绝大多数常规场景。
内容的提问来源于stack exchange,提问作者F Hughes
相关产品推荐
相关产品推荐

