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

新增文章时wp_after_insert_post钩子异常:$update参数始终返回true

解决wp_after_insert_post钩子新增文章时$update始终为true的问题

问题原因分析

新增service类型文章时$update参数始终返回true,大概率是因为新增操作后触发了二次文章更新:比如ACF字段保存、自定义逻辑修改文章元数据等,导致wp_after_insert_post钩子被触发两次——第一次新增时$update为false,但二次更新时$update变为true,而你可能误把第二次执行当成了新增的逻辑入口。

另外,WordPress内部的$update参数是基于wp_insert_post函数的传入值判断的,若有自动后续更新操作,该参数会被置为true,此时用它判断是否为新增文章并不可靠。

解决方案

方案1:用$post_before参数判断是否为新增文章

这是最可靠的判断方式:新增文章时$post_before为null,只有更新操作时才会传入更新前的WP_Post对象。修改你的钩子逻辑如下:

add_action( 'wp_after_insert_post', function( $post_id, $post, $update, $post_before ){
    if(get_post_type($post_id) == 'service' && $post->post_status == 'publish'){
        // 用$post_before判断是否为首次新增
        $is_new_post = is_null($post_before);
        
        if(!$is_new_post){
            // 原$update为true的逻辑(更新文章时执行)
            // Do something here
        }

        if($is_new_post){
            // 原新增文章时的逻辑
            $product = wc_get_product(get_field('product', $post_id));
             foreach($product->get_available_variations() as $variation){
                wc_get_product($variation['variation_id'])->delete();
            }
        }
        
        $plans = get_field('plans', $post_id);
        // 调整产品获取逻辑,匹配新增/更新场景
        $product = $is_new_post ? create_service_product($post->post_title) : wc_get_product(get_field('product', $post_id));
        
        $plan_names = [];
        if($plans){
            foreach($plans as $plan){
                $plan_names[] = $plan['name'];
            }
            $atts = [];
            $atts[] = create_attributes('plans', $plan_names);
            $product->set_attributes( $atts );
            $product->save();
            
            foreach($plans as $i => $plan){
                $var_id = create_variation( $product->get_id(), [ 'plans' => $plan['name'] ], $plan['price']);
                $row = [
                    'product_variation_id' => $var_id
                ];
                update_row('plans', $i + 1, $row);
            }
        }
        update_field('product', $product->get_id(), $post_id);
    }
}, 10, 4 );

方案2:排查二次更新触发源

检查是否有其他逻辑导致文章被自动二次更新:

  • 查看ACF字段设置,部分字段类型可能在保存时触发文章更新
  • 排查自定义的save_post、update_post_meta等钩子,确认是否在新增文章后修改了文章数据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 08:13:16