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

使用edit_post_applications钩子更新记录时出现重复新增问题求助

问题原因及解决方法

你的代码出现重复插入记录的核心原因是edit_post_applications钩子会被多次触发——WordPress在自动保存草稿、创建修订版本时,都会触发这个钩子,导致你的add_new_university函数执行两次,最终插入两条重复的institution类型帖子。

修复步骤

在函数开头添加判断逻辑,跳过自动保存和修订版本的触发场景:

add_action('edit_post_applications', 'add_new_university');

function add_new_university($id)
{
    // 跳过自动保存和修订版本的触发
    if (wp_is_post_autosave($id) || wp_is_post_revision($id)) {
        return;
    }

    $post_field = get_fields($id);

    return wp_insert_post(array(
        'post_type' => 'institution',
        'post_title' => get_post($id)->post_title,
        'post_status' => 'publish',
        'meta_input' => array(
            'full_name' => $post_field['full_name'],
            'short_name' => $post_field['short_name']
        ),
    ));
}

补充说明

如果更换钩子后仍有问题,大概率是没有处理自动保存/修订版本的判断逻辑。其他类似的帖子更新钩子(比如save_post_applications)也会存在同样的触发多次的情况,所以这个判断逻辑是通用的解决方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 14:38:15