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

WordPress自定义表单无法提交数据至数据库求助

自定义表单无法提交数据到WordPress文章类型的问题解决

问题现象

  • 表单提交后var_dump能正常输出数据,但WordPress后台文章列表无新增内容
  • 提交至默认post类型和自定义文章类型均失败

原formHandler.php代码

if(isset($_POST['submit'])){
    
    $berichtnaam = $_POST['berichtnaam'];
    $categories = array('kat', 'hond', 'slang');
    $categorie = $_POST['categorie'];
    $foto = $_FILES['foto'];
    $bericht = $_POST['bericht'];
    $post_content = array($categorie, $bericht);
    
    var_dump($berichtnaam);
    var_dump($foto);
    var_dump($post_content);

    $blog_post = (array(
        'post_status' => 'publish',
        'post_type' => 'post',
        'post_title' => wp_strip_all_tags($berichtnaam),
        'post_content' => $post_content
    ) );

    wp_insert_post($blog_post);
  
}

原表单代码

<form action="<?php echo get_template_directory_uri()?>/formHandler.php" method="post" enctype="multipart/form-data">
    <div class="mb-3">
        <label for="exampleFormControlInput1" class="form-label">Berichtnaam</label>
        <input type="text" class="form-control" id="exampleFormControlInput1" placeholder="Geen titel" name="berichtnaam">
    </div>

    <label for="select-field">Categorie</label>
        <select class="form-select form-control" id="select-field" aria-label="Default select example" name="categorie">
            <option selected>Geen categorie</option>
            <option value="kat">Kat</option>
            <option value="hond">Hond</option>
            <option value="slang">Slang</option>
        </select>

    <div class="mb-3" id="file_field">
            <label for="uploadFoto" id="input_file">
                <i class="fi fi-rr-camera"></i><span id="upload_btn">Kies bestand</span>
            </label>
            <input type="file" class="form-control" id="uploadFoto" onchange="showFileName()" name="foto">
            <p id="fileSelected"></p>
            <p id="fileUnSelected"></p>
    </div>

    <div class="mb-3">
                <label for="formGroupExampleInput2" class="form-label">Bericht</label><br>
                <textarea class="form-control" id="formGroupExampleInput2" name="bericht"></textarea>
            </div>

    <button id="card-L" type="submit" name="submit" value="submit">Bericht aanmaken</button>
</form>

曾尝试的解决方案

$blog_post = wp_insert_post(array(
        'post_status' => 'publish',
        'post_type' => 'post',
        'post_title' => wp_strip_all_tags($berichtnaam),
        'post_content' => $post_content
    ) );

$post_type = 'blogpost_vero';

$query = "UPDATE {$wpdb->prefix}posts SET post_type='".$post_type."' WHERE id='".$blog_post."' LIMIT 1";

GLOBAL $wpdb; 

$wpdb->query($query);

问题根源

  1. 未加载WordPress环境:直接访问formHandler.php时,WordPress核心函数(如wp_insert_post、$wpdb)未被初始化,函数无法执行,自然无法插入文章。
  2. post_content格式错误:wp_insert_post要求post_content参数为字符串,但你传入的是数组$post_content = array($categorie, $bericht),这会导致插入失败。

修复步骤

步骤1:修改表单提交地址

将表单的action改为WordPress内置的admin-post.php,确保能加载WP环境:

<form action="<?php echo admin_url('admin-post.php'); ?>" method="post" enctype="multipart/form-data">
    <!-- 新增隐藏字段,标识处理动作 -->
    <input type="hidden" name="action" value="submit_custom_post">
    <!-- 原表单内容保持不变 -->
    ...
</form>

步骤2:在主题functions.php中添加处理函数

在当前主题的functions.php文件末尾添加以下代码,处理表单提交:

// 处理自定义表单提交
add_action('admin_post_submit_custom_post', 'handle_custom_form_submission');
add_action('admin_post_nopriv_submit_custom_post', 'handle_custom_form_submission'); // 允许未登录用户提交

function handle_custom_form_submission() {
    if (!isset($_POST['submit'])) {
        wp_redirect($_SERVER['HTTP_REFERER']);
        exit;
    }

    // 获取并过滤表单数据
    $berichtnaam = isset($_POST['berichtnaam']) ? wp_strip_all_tags($_POST['berichtnaam']) : '';
    $categorie = isset($_POST['categorie']) ? wp_strip_all_tags($_POST['categorie']) : '';
    $bericht = isset($_POST['bericht']) ? wp_kses_post($_POST['bericht']) : '';

    // 转换post_content为字符串格式
    $post_content = !empty($categorie) ? "分类:{$categorie}\n\n{$bericht}" : $bericht;

    // 准备文章参数
    $post_args = array(
        'post_status' => 'publish',
        'post_type' => 'post', // 如需自定义文章类型,替换为你的类型名,比如'blogpost_vero'
        'post_title' => $berichtnaam ?: '无标题',
        'post_content' => $post_content
    );

    // 插入文章
    $post_id = wp_insert_post($post_args);

    // 可选:绑定分类(默认分类法)
    if (!empty($categorie) && $post_id) {
        $cat_term = get_term_by('slug', $categorie, 'category');
        if ($cat_term) {
            wp_set_post_categories($post_id, array($cat_term->term_id));
        }
    }

    // 提交后跳转回原页面
    wp_redirect($_SERVER['HTTP_REFERER']);
    exit;
}

步骤3:验证修复效果

  1. 提交表单后,进入WordPress后台文章列表,即可看到新增的文章
  2. 如需提交到自定义文章类型,只需修改$post_args中的post_type值为你的自定义类型名称,无需手动修改数据库

补充说明

  • 暂时未处理文件上传,待数据提交问题解决后,可使用wp_handle_upload函数处理$_FILES['foto'],并通过set_post_thumbnail设置为文章特色图片
  • 代码中使用wp_kses_post和wp_strip_all_tags过滤用户输入,避免XSS安全问题,符合WordPress开发规范

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 17:27:36