PHP 8.0升级后count()触发TypeError错误,寻求解决方案
解决方案
问题原因
PHP 8.0 对 count() 函数的参数类型做了严格限制,仅允许传入可数类型(Countable)或数组。你的代码中 get_field('news_detail_related_posts', $post->ID) 可能返回了 false(比如字段未配置、无内容或获取失败),布尔值不属于可数类型,因此触发致命错误。
可行修复方案
方案1:先校验类型再计数
先把字段值赋值给变量,用 is_countable() 校验后再调用 count():
$related_posts = get_field('news_detail_related_posts', $post->ID); if (is_countable($related_posts) && count($related_posts) > 0):
方案2:用空合并运算符转为空数组
直接将非数组/非可数的返回值转为空数组,确保 count() 始终接收合法参数:
if(count(get_field('news_detail_related_posts', $post->ID) ?: []) > 0):
?: 会在左侧值为 false、null 等空值时,返回右侧的空数组。
方案3:结合 !empty() 简化判断
如果仅需要判断是否有有效内容,可直接用 !empty() 结合类型检查:
$related_posts = get_field('news_detail_related_posts', $post->ID); if (!empty($related_posts) && is_countable($related_posts)):
补充说明
ACF 的 get_field() 函数在字段不存在或无值时会返回 false,PHP 7.x 版本会默认将 false 视为 0 处理,但 PHP 8.0 开始启用严格类型校验,因此必须先处理返回值的类型合法性。
内容的提问来源于stack exchange,提问作者francisco
相关产品推荐
相关产品推荐

