wp_after_insert_post is not working properly while adding new post. The $update parameter always returns true, despite adding new post.
do_action( ‘wp_after_insert_post’, int $post_id, WP_Post $post, bool $update, null|WP_Post $post_before )
UPDATE - here is the action
add_action( 'wp_after_insert_post', function( $post_id, $post, $update, $post_before ){
if(get_post_type($post_id) == 'service' && $post->post_status == 'publish'){
if($update){
// Do something here, but $update is always true despite it is new post insert or update
}
$post_exist = $update ? false : true;
if($post_exist){
$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 = $post_exist ? wc_get_product(get_field('product', $post_id)) : create_service_product($post->post_title);
$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 );
If you are adding a post via the Dashboard, because WordPress creates revisions automatically, $update is going to always be true, even when you first publish the post.
One way to determine if this is a new post is to compare the post_date to the current day and time. Here is how I would do it inside your callback function:
$current_time = current_time('timestamp', true); // no GMT offset
$publish_time = get_post_timestamp( $post_id ); // also, no GMT offset
if( ($current_time - $publish_time) < 30 ){
// this post was published less than 30 seconds ago - it's new
}