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

WordPress手动插入数据库数据:表单提交未触发functions.php函数问题排查求助

WordPress手动插入数据库数据:表单提交未触发functions.php函数问题排查求助

我正在跟着教程手动实现WordPress表单提交数据到数据库的功能,但遇到了一个棘手的问题:表单的提交按钮似乎完全没触发functions.php里的处理函数,数据库里没有任何新增数据,而且我加的调试日志也一条都没出现在error log里,看起来整个处理流程根本没启动。以下是我用到的代码和目前的情况,希望能帮我找出问题所在!

我的表单代码

<form method="post">
  <div class="form-group">
    <label for="workoutdate">Workout Date</label>
    <input id="workoutdate" name="workoutdate" type="date" class="form-control input-sm" required="">
  </div>
  <div class="form-group">
    <label for="activity">Activity</label>
    <input id="activity" name="activity" type="text" placeholder="activity" class="form-control input-sm" required="">
  </div>
  <div class="form-group">
    <label for="time_mins">time in mins</label>
    <input id="time_mins" name="time_mins" type="text" class="form-control input-sm" required="">
  </div>
  <div class="form-group">
    <input id="user_id" name="user_id" type="hidden" value="<?php echo get_current_user_id();?> class="form-control input-sm" required="">
  </div>
  <div class="row justify-content-center">
    <div class="col-xs-4 col-sm-4 col-md-4">
      <input type="submit" value="Submit" class="btn btn-info btn-block" name="workoutformbtn">
    </div>
  </div>
</form>

functions.php里的处理代码

add_action('template_redirect', function() {
    //Make sure it's our form
    if(isset($_POST['workoutformbtn'])) {
        //These Next 4 Lines Are For Debugging
        // error_log("workoutdate");
        error_log($_POST['activity']);
        error_log($_POST['time_mins']);
        error_log($_POST['user_id']);

        //Create array of the form fields to pass to PHP page that will handle inserting new data into database table
        $fields = array(
            'workoutdate' => $_POST['workoutdate'],
            'activity' => $_POST['activity'],
            'time_mins' => $_POST['time_mins'],
            'user_id' => $_POST['user_id']
        );

        //This calls the php file that will insert the data into your database table
        wp_remote_post('http://pickleball-league.local/wp-content/themes/astra/create_workout.php',['body' => $fields,]);

        //After data is inserted into the database, you direct them back to the workout
        wp_safe_redirect('http://pickleball-league.local/my_workout/');
    }
},10);

配套的create_workout.php代码

<?php
include 'mydbfile.php';

$workoutdate = $_POST["workoutdate"];
$activity = $_POST["activity"];
$time_mins = $_POST["time_mins"];
$user_id = $_POST["user_id"];

//next 4 lines are for debugging, they appear in the php error.log file
//comment them out before putting into production
error_log('workoutdate = '.$workoutdate);
error_log('activity = '.$activity);
error_log('time_mins = '.$time_mins);
error_log('user_id = '.$user_id);

echo "<h1>test</h1>";

$sql = "INSERT INTO my_workouts(user_id,workout_date,activity,time_mins)VALUES ('$user_id','$workoutdate','$activity','$time_mins')";
error_log('sql='.$sql);
print_r($sql);

$conn->query($sql);
$conn->close();
?>

表单下方的JS代码

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
jQuery(document).on('submit_success',function(event,response){
    read();
});
jQuery(document).ready(function($){
    read();
});
function getReadUrl(){
    var params = new URLSearchParams(window.location.search);
    var url="/wp-content/themes/astra/read_workouts.php";
    if(params.has('id')){
        url=url + "?id="+params.get('id');
    }
    return url;
}
function read(){
    var url = getReadUrl();
    $.get(url,function(data){
        document.getElementById("records").innerHTML = data;
    });
}
</script>

目前我是在本地环境搭建的,没法展示实际效果。我怀疑过是不是本地JS禁用了,但不知道怎么测试。我已经确认create_workout.php的路径是对的,但问题是根本没走到调用这个文件的步骤。


梳理的排查方向,你可以逐一验证:

  1. 表单隐藏字段的语法错误(最可能的原因)
    看你的user_id隐藏输入框代码:

    <input id="user_id" name="user_id" type="hidden" value="<?php echo get_current_user_id();?> class="form-control input-sm" required="">
    

    这里明显有语法问题:value属性的PHP代码后没有闭合双引号,直接衔接了class属性,会导致浏览器解析HTML出错,不仅user_id的值会变成混乱的字符串,甚至可能破坏整个表单的结构,导致提交时无法正确携带workoutformbtn参数,自然触发不了functions.php里的判断。

    修正后的代码应该是:

    <input id="user_id" name="user_id" type="hidden" value="<?php echo get_current_user_id();?>" class="form-control input-sm" required="">
    
  2. 确认调试日志功能正常
    先在functions.php的判断块最开头加一行简单的日志:

    if(isset($_POST['workoutformbtn'])) {
        error_log("=== Workout form submit detected ===");
        // 其他原有代码...
    }
    

    然后提交表单,去PHP的error log里找这条日志。如果没有,说明请求根本没进入这个判断分支;如果有,再排查后续的wp_remote_post或数据库插入逻辑。

    另外要确认你的PHP error log路径是正确的,比如可以随便加一行error_log("Test log entry");在functions.php的全局范围,看是否能记录到日志,排除日志功能本身的问题。

  3. 补充WordPress安全验证(Nonce)
    WordPress默认会对无验证的请求有拦截机制,你的表单没有添加CSRF验证的Nonce,可能被主题或安全插件拦截。建议加上Nonce:

    • 在表单里添加隐藏字段:
      <?php wp_nonce_field( 'workout_form_action', 'workout_form_nonce' ); ?>
      
    • 在functions.php的判断里加上验证:
      if( isset($_POST['workoutformbtn']) && wp_verify_nonce( $_POST['workout_form_nonce'], 'workout_form_action' ) ) {
          // 原有处理代码...
      }
      
  4. 明确表单的提交目标
    你的表单没有设置action属性,默认提交到当前页面,但如果是自定义模板页面,可能存在URL解析问题。可以明确指定action:

    <form method="post" action="<?php echo esc_url( $_SERVER['REQUEST_URI'] ); ?>">
    
  5. 排除JS或插件/主题的干扰

    • 检查表单提交后页面是否刷新:如果没刷新,说明有JS阻止了原生提交行为,可以暂时移除表单下方的JS代码,测试原生提交是否正常。
    • 暂时禁用所有WordPress插件,切换到默认主题(如Twenty Twenty-Three),排除第三方代码的拦截。
  6. 测试JS是否启用
    可以在页面上加一段简单的测试代码:

    <script>
        alert("JS is working!");
    </script>
    

    打开页面如果能弹出提示,说明JS是正常启用的。

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.07 10:54:28