WooCommerce价格筛选小部件报错:读取null的min_price/max_price属性
我搭建了一个简易电商网站,上传了约100个简单产品。初期无问题,但上传约60个产品后出现如下警告:
Warning: Attempt to read property "min_price" on null in C:\xampp\htdocs\wordpress\wp-content\plugins\woocommerce\includes\widgets\class-wc-widget-price-filter.php on line 91
Warning: Attempt to read property "max_price" on null in C:\xampp\htdocs\wordpress\wp-content\plugins\woocommerce\includes\widgets\class-wc-widget-price-filter.php on line 92
警告指向的代码行如下:
//89 Find min and max price in current result set. //90 $prices = $this->get_filtered_price(); //91 $min_price = $prices->min_price; //92 $max_price = $prices->max_price;
已尝试的无效方案
- 曾参考相关解决方案,尝试插入一段按价格范围筛选产品的PHP代码,但因不熟悉PHP,不清楚正确插入位置(曾尝试插入到WooCommerce文件夹的functions.php中),未解决问题。
- 收到过更新WordPress或WooCommerce的建议,但对此存疑。
- 有人认为可变产品会导致该问题,但确认所有产品均为简单产品类型。
问题根源分析
这个警告本质是$this->get_filtered_price()方法返回了null,导致后续无法读取min_price和max_price属性。常见原因包括:
- 部分产品价格数据异常(比如价格未设置、价格为非数值)
- 产品查询时出现错误,导致无法获取价格数据集
- WooCommerce小部件的价格筛选逻辑在特定产品数量下出现漏洞
具体解决步骤
排查产品价格数据
- 批量检查所有产品的价格设置,确保每个简单产品都正确填写了常规价格,没有空值、非数字内容。
- 可以用WooCommerce的产品导出功能,导出所有产品的CSV文件,筛选价格列快速排查异常数据。
修复价格筛选小部件的空值判断
不建议直接修改WooCommerce核心文件,而是通过主题的functions.php添加钩子来修正:add_filter( 'woocommerce_widget_price_filter_get_filtered_price', 'fix_price_filter_null_return', 10, 2 ); function fix_price_filter_null_return( $prices, $widget ) { if ( is_null( $prices ) ) { // 当获取失败时,手动查询所有可见产品的价格范围 $args = array( 'status' => 'publish', 'limit' => -1, 'return' => 'ids', ); $product_ids = wc_get_products( $args ); if ( ! empty( $product_ids ) ) { $min_price = PHP_INT_MAX; $max_price = 0; foreach ( $product_ids as $id ) { $product = wc_get_product( $id ); if ( $product ) { $price = (float) $product->get_price(); $min_price = min( $min_price, $price ); $max_price = max( $max_price, $price ); } } $prices = (object) array( 'min_price' => $min_price, 'max_price' => $max_price, ); } else { // 没有产品时设置默认值 $prices = (object) array( 'min_price' => 0, 'max_price' => 0, ); } } return $prices; }这段代码的作用是:当价格筛选小部件获取价格数据返回null时,手动查询所有已发布产品的价格,生成有效的价格范围对象,避免警告出现。
验证WooCommerce与WordPress兼容性
如果上述方法无效,建议先备份网站数据,再更新到兼容的WordPress和WooCommerce版本——旧版本可能存在已知的价格筛选逻辑bug,更新是最直接的修复方式。排查插件冲突
暂时禁用除WooCommerce外的所有插件,刷新页面看警告是否消失。如果消失,再逐个启用插件,找到冲突的插件后更新或替换它。
内容的提问来源于stack exchange,提问作者Resai

