求助:WordPress Options Framework插件PHP非法字符串警告如何修复
修复Options Framework Plugin的PHP警告问题
问题原因
PHP7.4及以上版本对函数参数类型检查更严格,旧版PHP会隐式将字符串转换为数组(无警告),但新版本会抛出array_keys() expects parameter 1 to be array警告。你的情况中,$heading_weights被读取为空格分隔的字符串" 1 1",而非预期的数组结构。
代码修复方案
修改functions.php中对应代码段,先对变量做类型校验和转换,再执行array_keys操作:
588 $heading_weights = of_get_option( 'heading_font_weights', options_typography_get_font_weights() ); 589 $body_weights = of_get_option( 'body_font_weights', options_typography_get_font_weights() ); 590 591 // 处理heading_weights的类型兼容,适配PHP7.4+ 592 if (!is_array($heading_weights)) { 593 // 去除首尾空格后按空格分割,过滤空元素 594 $weight_items = array_filter(explode(' ', trim($heading_weights))); 595 // 转换为原主题预期的键值对数组(键为权重值,值为true) 596 $heading_weights = array_combine($weight_items, array_fill(0, count($weight_items), true)); 597 } 598 599 $heading_weights_values = array_keys($heading_weights, true);
额外优化(可选)
为避免$body_weights后续出现同样问题,可同步添加类型处理:
// 同步处理body_weights if (!is_array($body_weights)) { $body_weight_items = array_filter(explode(' ', trim($body_weights))); $body_weights = array_combine($body_weight_items, array_fill(0, count($body_weight_items), true)); }
修复逻辑说明
- 类型校验:用
is_array()判断变量是否为数组,非数组则进入转换流程 - 字符串转数组:通过
trim()去除首尾空格,explode(' ')按空格分割字符串,array_filter()过滤连续空格产生的空元素 - 还原预期结构:用
array_combine()将权重值作为数组键,array_fill()生成对应数量的true值,还原主题原本预期的数组结构,确保array_keys()能正常执行
内容的提问来源于stack exchange,提问作者KKranzo
相关产品推荐
相关产品推荐

