PHP7.4升级到PHP8.1后WordPress空对象属性赋值错误求助
问题:WordPress从PHP7.4升级到PHP8.1后出现致命错误
升级后触发如下致命错误:
Fatal error: Uncaught Error: Attempt to assign property "posts" on null in TEMPLATEFILE on line 93
涉及报错的代码行:
Line 93 $query_txt_ref->posts = array(); Line 98 $query_book->posts = array(); Line 224 $query_txt_ref_others->posts = array(); Line 232 $query_others->posts = array();
更多参考代码:
add_filter('posts_where', 'where_text_refrence'); add_filter('posts_join','join_text_refrence'); $query_txt_ref->posts = array(); $query_txt_ref = new WP_Query($args_daily_devotion_txt_ref); remove_filter('posts_where', 'where_text_refrence'); remove_filter('posts_join', 'join_text_refrence'); $query_book->posts = array(); add_filter('posts_where', 'where_botb_tags'); $query_book = new WP_Query($args_daily_devotion); remove_filter('posts_where', 'where_botb_tags');
解决方案
- 核心问题:PHP8.0及以上版本对未初始化变量的属性赋值会直接抛出致命错误,而PHP7.4及之前仅会触发警告,不会终止程序运行。原代码中变量在实例化
WP_Query前是未定义的null,因此赋值->posts会触发错误。 - 修改方式:将
$query->posts = array();移到new WP_Query()实例化语句之后,确保变量是有效的WP_Query对象再赋值。
修正后的代码示例:
add_filter('posts_where', 'where_text_refrence'); add_filter('posts_join','join_text_refrence'); // 先实例化WP_Query对象 $query_txt_ref = new WP_Query($args_daily_devotion_txt_ref); // 再给posts属性赋值 $query_txt_ref->posts = array(); remove_filter('posts_where', 'where_text_refrence'); remove_filter('posts_join', 'join_text_refrence'); // 同理修正第二个查询 add_filter('posts_where', 'where_botb_tags'); $query_book = new WP_Query($args_daily_devotion); $query_book->posts = array(); remove_filter('posts_where', 'where_botb_tags');
内容的提问来源于stack exchange,提问作者Vic Hechanova
相关产品推荐
相关产品推荐

