WordPress结账系统PHP报Undefined index及null偏移错误如何解决?
报错根因
两个报错均指向代码第3行,核心原因是直接访问了可能不存在的数组键$args['quote']['answers']:当$args['quote']数组中没有answers这个键,或者answers的值为null时,直接读取$args['quote']['answers']['planPremioMensual']就会触发未定义索引、null类型访问数组偏移的提示。
修复方案
我们需要对所有依赖answers的字段加默认值、统一做存在性判断,修改后的完整fragment-header.php代码如下:
<?php // 先统一判断answers是否存在且为数组,提前设置默认值 $answers = $args['quote']['answers'] ?? []; $valorAccesorio = $answers['vehicleGncValue'] ?? '0'; $planPremioMensual = $answers['planPremioMensual'] ?? 0; $apPremioMensual = $answers['apPremioMensual'] ?? 0; $cuotaMensual = $planPremioMensual + $apPremioMensual; ?> <header id="header"> <div class="wrap menu-wrap"> <?php $class = (theme_get_custom_logo()) ? 'image' : 'text'; echo '<h1 class="site-title ' . $class . '">'; echo '<a href="' . esc_url(home_url('/')) . '" rel="home">'; if (theme_get_custom_logo()) echo '<img src="' . theme_get_custom_logo() . '" class="site-logo" alt="' . htmlspecialchars(get_bloginfo('name')) . '" />'; echo '<strong>' . get_bloginfo('name') . '</strong>'; echo '</a>'; echo '</h1>'; ?> <div class="right-section"> <?php // 新增answers非空判断,避免无数据时后续代码报错 $product = $args['quote']['product'] ?? ''; if (($product == 'seguro-de-motos' || $product == 'seguro-de-autos-y-pick-ups') && !empty($answers)) : ?> <h1> Estás contratando un plan <span><?php echo $answers['planCobertura'] ?? ''; ?></span>, para tu <span> <?php echo $answers['vehicleBrand'] ?? ''; ?> <?php if (isset($answers['vehicleModel'])) { echo $answers['vehicleModel']; } else { echo $answers['vehicleVersion'] ?? ''; } ?> <?php echo $answers['vehicleYear'] ?? ''; ?> </span> </h1> <p> Suma asegurada: $<?php echo number_format(($answers['vehicleValue'] ?? 0 + $valorAccesorio), 2, ',', '.') ?> | Cuota mensual: $<?php echo number_format($cuotaMensual, 2, ',', '.') ?> </p> <?php endif; ?> </div>
修改说明
- 提前把
$args['quote']['answers']赋值给变量$answers,不存在就默认赋值空数组,避免后续重复写多层数组访问逻辑 - 所有从
answers读取的字段都用??设置默认值,彻底避免未定义索引报错 - 渲染右侧产品信息的条件判断新增
$answers非空校验,无报价数据时不渲染对应内容,不会抛出报错 - 同步修复了
$args['quote']['product']可能不存在的潜在报错问题
内容的提问来源于stack exchange,提问作者Mario
相关产品推荐
相关产品推荐

