在自定义PHP函数中运行SQL prepared语句

时间:2017-05-19 23:48:07

标签: php mysql wordpress

我编写了以下函数,在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);

1 个答案:

答案 0 :(得分:0)

我最后添加了另一个操作(编辑和保存)来更新产品。

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