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

通过ACF表单新建文章时如何更新原关联文章的指定ACF字段

问题原因

你当前代码的核心问题有两个:

  1. acf/save_post 钩子触发时拿到的$post_id是新生成的「文章B」的ID,没有传递「文章A」的ID信息,无法定位到需要更新的目标文章
  2. 调用update_field函数时没有传入第三个参数「目标文章ID」,默认只会更新当前钩子对应的「文章B」的字段

解决步骤

步骤1:在「文章A」的ACF表单中添加隐藏字段传递当前文章ID

你在调用acf_form渲染表单的位置,添加参数传递当前文章A的ID作为隐藏字段提交:

acf_form(array(
    // 保留你原本的表单配置(比如'post_id' => 'new_post'、'new_post' => 你的自定义文章类型配置等
    // 新增以下配置插入隐藏字段
    'html_before_fields' => '<input type="hidden" name="source_post_id" value="'.esc_attr(get_the_ID()).'">',
));

步骤2:修改acf/save_post钩子逻辑,更新来源文章字段

替换你原有代码为以下内容:

<?php 
add_action('acf/save_post', 'update_source_post_submit_status', 20);

function update_source_post_submit_status( $post_id ) {
    // 过滤非目标文章类型的提交,和你原有逻辑保持一致
    if( get_post_type($post_id) !== 'mypost' ) {
        return;
    }

    // 校验提交的来源文章ID合法性
    if (isset($_POST['source_post_id']) && is_numeric($_POST['source_post_id'])) {
        $source_post_id = intval($_POST['source_post_id']);
        // 可选添加:额外校验来源文章的类型是否符合你的业务要求
        // if (get_post_type($source_post_id) !== 'post') return;

        // 第三个参数传入来源文章A的ID,更新对应字段
        update_field('form_submitted', 'yes', $source_post_id);
    }
}
?>

步骤3:前端判断是否显示表单

后续在文章页渲染表单前,先判断字段值即可实现仅提交一次的效果:

$has_submitted = get_field('form_submitted');
if ($has_submitted !== 'yes') {
    // 输出ACF表单
    acf_form(你的表单配置);
} else {
    echo '<p>该表单已提交,无需重复操作</p>';
}

可选优化

为了防止恶意篡改隐藏字段的值,你可以添加nonce校验提升安全性:
在html_before_fields配置中新增nonce字段:

'html_before_fields' => '<input type="hidden" name="source_post_id" value="'.esc_attr(get_the_ID()).'">'.wp_nonce_field('submit_form_'.get_the_ID(), 'submit_nonce', true, false),

然后在钩子函数中新增校验逻辑:

if (!isset($_POST['submit_nonce']) || !wp_verify_nonce($_POST['submit_nonce'], 'submit_form_'.$source_post_id)) {
    return;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 08:15:03