WordPress无评论商品隐藏星级评分时出现PHP致命错误排查
错误原因与代码问题分析
错误原因
报错Call to a member function get_id() on null的核心原因是:body_class过滤器会在全站所有页面触发执行,但global $product仅在WooCommerce商品详情页会被正确初始化。当代码运行在非商品页面(比如首页、博客列表页、分类归档页等)时,$product变量为null,此时调用$product->get_id()就会触发致命错误。
代码存在的问题
- 缺少变量有效性校验:直接调用
global $product后未检查其是否为有效对象,导致非商品页面执行时崩溃。 - 评论查询效率低下:通过
get_comments()加载整个评论数组判断是否为空,不如直接调用get_comments_number()获取评论数量高效,无需加载冗余数据。 - 全局变量依赖不可靠:过度依赖
$product全局变量,兼容性差,不如直接使用WordPress原生$post对象获取当前文章ID稳定。
修正后的代码方案
步骤1:替换原有PHP代码片段
function check_for_empty_stars( $classes ) { // 仅在单个商品详情页执行逻辑 if ( is_singular( 'product' ) && get_post_type() === 'product' ) { $post_id = get_the_ID(); // 获取当前商品的评论总数 $comment_count = get_comments_number( $post_id ); // 评论数为0时添加目标body类 if ( $comment_count === 0 ) { $classes[] = 'hide-empty-stars'; } } return $classes; } add_filter( 'body_class', 'check_for_empty_stars' );
步骤2:保留原有CSS代码(无需修改)
body.hide-empty-stars .star-rating{ display: none; }
修正点说明
- 页面范围限制:通过
is_singular('product')和get_post_type()双重判断,确保代码仅在单个商品详情页执行,避免非商品页面触发错误。 - 可靠获取ID:使用
get_the_ID()直接获取当前文章ID,无需依赖$product全局变量,兼容性更强。 - 高效判断评论状态:用
get_comments_number()获取评论数,相比加载全部评论数组性能更优,逻辑更直接。
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

