[英]Run SQL prepared statement in custom PHP function
我編寫了以下函數,以在wordpress中使用PHP創建woocommerce產品,並在添加/更新自定義帖子類型后將其刪除的情況下將其刪除。
如果我在帖子頁面中按兩次“更新”按鈕,一切工作正常,就好像我應該兩次運行代碼一樣。 誰能幫我嗎。
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);
最后,我添加了另一個操作(“編輯並保存”)以更新產品。
add_action('edit_post', 'create_tour_product',10,2);
add_action('save_post', 'create_tour_product',10,2);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.