
WordPress 主题升级 PHP 版本后,因 get_option() 返回 false 却直接当作数组访问,导致“Trying to access array offset on value of type bool”错误,本文提供安全、健壮的修复方案。
wordpress 主题升级 php 版本后,因 `get_option()` 返回 `false` 却直接当作数组访问,导致“trying to access array offset on value of type bool”错误,本文提供安全、健壮的修复方案。
该错误本质是 PHP 8.0+ 严格类型校验增强后的典型问题:当 get_option('theme_opt') 未找到对应选项(如主题设置未保存、数据库缺失或插件未激活),函数返回 false 而非空数组;此时若直接使用 $lyara_opt['product_per_page'],即等同于 false['product_per_page'],PHP 将抛出致命警告。
✅ 正确写法:始终验证选项数据类型
在 functions.php 的 lyara_woo_change_per_page() 函数中,需先判断 $lyara_opt 是否为有效数组:
function lyara_woo_change_per_page() {
$lyara_opt = get_option( 'theme_opt' );
// 安全检查:确保 $lyara_opt 是非空数组且含目标键
if ( is_array( $lyara_opt ) && isset( $lyara_opt['product_per_page'] ) && is_numeric( $lyara_opt['product_per_page'] ) ) {
return (int) $lyara_opt['product_per_page'];
}
// 回退值:推荐设为 WooCommerce 默认值(e.g., 12)或主题合理默认值
return 12;
}
? 同理修复 content-product-archive.php 中的隐患
原代码中 $theme_opt 变量来源未明(疑似未定义或未初始化),且未做类型校验,直接 isset($theme_opt) 不足以防止 bool 类型误用(例如 $theme_opt = false 时 isset() 仍返回 true)。应统一采用 is_array() + isset() 双重校验:
$colwidth = 3;
if ( $theme_shopclass === 'shop-fullwidth' ) {
$theme_opt = get_option( 'theme_opt' );
if ( is_array( $theme_opt ) && isset( $theme_opt['product_per_row_fw'] ) && $theme_opt['product_per_row_fw'] > 0 ) {
$woocommerce_loop['columns'] = (int) $theme_opt['product_per_row_fw'];
$colwidth = (int) round( 12 / $woocommerce_loop['columns'] );
}
$classes[] = ' item-col col-6 col-md-4 col-xl-' . $colwidth;
} else {
$theme_opt = get_option( 'theme_opt' );
if ( is_array( $theme_opt ) && isset( $theme_opt['product_per_row'] ) && $theme_opt['product_per_row'] > 0 ) {
$woocommerce_loop['columns'] = (int) $theme_opt['product_per_row'];
$colwidth = (int) round( 12 / $woocommerce_loop['columns'] );
}
$classes[] = ' item-col col-6 col-sm-6 col-md-4 col-xl-' . $colwidth;
}
? 优化建议:
- 将 get_option('theme_opt') 提取为一次调用并复用,避免重复查询;
- 使用 (int) 强制类型转换,防止非数字字符串引发除零或计算异常;
- 在主题激活/设置保存时,确保 'theme_opt' 选项已初始化(可通过 add_option() 设置默认值);
- 开发阶段开启 WP_DEBUG_LOG,配合日志排查未初始化选项。
遵循以上实践,即可彻底规避 PHP 8+ 下因松散类型处理导致的数组偏移警告,提升主题兼容性与健壮性。
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!











