Add a post when another post type is inserting

The issue with your code appears to be related to the hook wp_after_insert_post being nested within the publish_service action. This setup can lead to the wp_after_insert_post action being added multiple times, which may cause the repeated creation of products.

Here are a few steps to resolve this issue:

Separate the Actions: Instead of nesting wp_after_insert_post within publish_service, consider separating them. This will prevent the inner action from being registered multiple times.

Check for Post Type: Ensure that the code runs only for the ‘service’ post type. This prevents the code from running for other post types.

Avoid Infinite Loops: When updating a post within a hook that triggers on post save or update, you must prevent an infinite loop. This can be done by removing the action before making changes to the post and then re-adding it afterward.

Product Creation and Updating Logic: Make sure your logic for creating or updating the product is correct. This includes checking if the product already exists and updating it if necessary, or creating a new one if it doesn’t.

Here is an updated version of your code considering these points:

add_action( 'publish_service', function( $post_id, $post ) {
    if ( 'service' !== get_post_type( $post_id ) ) {
        return;
    }

    $product_exist = get_field('product_id', $post_id) ? true : false;

    if ($product_exist) {
        // Logic for updating the existing product
        $product = wc_get_product(get_field('product_id', $post_id));
        foreach ($product->get_available_variations() as $variation) {
            wc_get_product($variation['variation_id'])->delete();
        }
    } else {
        // Logic for creating a new product
        create_service_product($post->post_title);
    }

    // Your additional logic here (like handling plans)
}, 10, 2);

function create_service_product($post_title) {
    // Logic for creating a new WooCommerce product
    // Return the new product ID or object
}

In this updated code:

The action is only attached to publish_service.
The product creation or update logic is executed directly in the publish_service action.
It checks if the post type is ‘service’ before proceeding.
The separate function create_service_product is assumed to handle the creation of a new product.
Remember to test this on a staging environment first before deploying it to a live site.

deneme bonusu veren sitelerbahis siteleripulibet girişdeneme bonusutürkçe altyazılı pornocanlı bahis casinocanlı bahis casino siteleriOnwin Güncel Girişholiganbetholiganbet girişholiganbet güncel girişnewsnewsnewsnewsnewsnewsnewsnewsnewsnewsnewsnewsnewsnewsnewsnewsnewsnewsnewsnewsnewsnews