I wrote the following function to create a woocommerce product with PHP in wordpress and delete it if it already exists upon add/update custom post type.

Everything is working fine if i pressed the “update button” twice as if i should run the code twice. Can anyone help me out.

function create_tour_product($post, $ID){

   if(get_post_type( $post ) == 'tour'){

    global $wpdb;

    $tourprice =get_post_meta( get_the_ID(), 'tour_price', true );
    $tourdiscountprice =get_post_meta( get_the_ID(), 'tour_discount_price', true );
    $tourname =get_the_title();
    $postimgid =get_the_ID();

    $sqlstatement = $wpdb->prepare("DELETE p FROM $wpdb->posts p join $wpdb->postmeta pm on p.ID = pm.post_id WHERE p.post_type = %s and p.post_title= %s",'product',$tourname);
    $wpdb->query($sqlstatement);

$new_product = array(
    'post_author' => $user_id,
    'post_content' => '',
    'post_status' => "publish",
    'post_title' => $tourname,
    'post_parent' => '',
    'post_type' => "product",
);


$new_product = wp_insert_post( $new_product, $wp_error );

if($new_product){

    $attach_id = get_post_thumbnail_id($postimgid);
    set_post_thumbnail($new_product, $attach_id);
    $tour_id = $new_product;
}

wp_set_object_terms( $new_product, 'Tours', 'product_cat' );
wp_set_object_terms( $new_product, 'simple', 'product_type');
update_post_meta( $new_product, '_visibility', 'visible' );
update_post_meta( $new_product, '_stock_status', 'instock');
update_post_meta( $new_product, 'total_sales', '0');
update_post_meta( $new_product, '_downloadable', 'no');
update_post_meta( $new_product, '_virtual', 'yes');
update_post_meta( $new_product, '_regular_price', $tourprice );
update_post_meta( $new_product, '_sale_price', $tourdiscountprice );
update_post_meta( $new_product, '_purchase_note', "" );
update_post_meta( $new_product, '_featured', "no" );
update_post_meta( $new_product, '_sku', "");
update_post_meta( $new_product, '_product_attributes', array());
update_post_meta( $new_product, '_price', $tourprice );
update_post_meta( $new_product, '_manage_stock', "no" );
update_post_meta( $new_product, '_backorders', "no" );

    }
}

add_action('edit_post', 'create_tour_product',10,2);

Read more here: Run SQL prepared statement in custom PHP function


Solution:

If you know the solution of this issue, please leave us a reply in Comment section, to update the question.


Wordpress related questions and answers: