You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

网站页脚出现Undefined index: product_id错误求修复

修复WordPress页脚的Undefined Index错误

这个错误的核心原因是代码直接访问$_GET['product_id'],但当URL中不存在这个GET参数时,PHP会抛出"Undefined index"通知——因为你试图访问一个不存在的数组键。以下是两种修复方案:

方案一:基础安全修复

先检查参数是否存在,再做非空判断,同时加入WordPress安全过滤:

<?php wp_footer(); 
// 先验证product_id是否存在,再判断是否为有效非空值
if(isset($_GET['product_id']) && trim($_GET['product_id']) !== ""){
    $product_id = sanitize_text_field($_GET['product_id']); // 过滤输入,防止XSS
    echo '<input type="hidden" id="product_id" value="'.$product_id.'" />';
    echo '<input type="hidden" id="product_name" value="'.esc_attr(get_the_title($product_id)).'" />'; // 转义输出内容
}
?>

方案二:使用WordPress原生函数(推荐)

如果product_id是WordPress查询参数的一部分,用get_query_var更符合WP开发规范:

<?php wp_footer(); 
$product_id = get_query_var('product_id');
if($product_id && trim($product_id) !== ""){
    $product_id = sanitize_text_field($product_id);
    echo '<input type="hidden" id="product_id" value="'.$product_id.'" />';
    echo '<input type="hidden" id="product_name" value="'.esc_attr(get_the_title($product_id)).'" />';
}
?>

关键说明

  • isset():用于判断$_GET数组中是否存在product_id键,彻底消除Undefined index通知;
  • sanitize_text_field()/esc_attr():WordPress安全函数,过滤输入、转义输出,避免跨站脚本攻击(XSS);
  • trim():排除参数值全为空格的无效情况。

内容的提问来源于stack exchange,提问作者Promnitech Digital

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 19:57:37