我在 Wordpress 中有以下功能。但是,每次更新帖子时都会复制元键product_price 。
喜欢这张图片
有什么办法可以防止这种情况发生吗?
function do_my_stuff($post_ID) {
global $post,$wpdb;
$tablename="wp_cart66_products";
if($post->post_type == "post" && strlen( get_post_meta($post_ID, 'price', true))>0 )
{
$id = $wpdb->get_var("SELECT id FROM ".$tablename." WHERE id=".$post_ID);
$cny = get_post_meta($post->ID, 'price', true);
/*Shipping rate */
if( $cny < 50 )
$shipping = 14.97;
else if( $cny >= 50 && $cny < 200 )
$shipping = 22.59;
else if( $cny >= 200 && $cny < 250 )
$shipping = 24.59;
else if( $cny >= 250 && $cny < 300 )
$shipping = 26.60;
else if( $cny >= 300 )
$shipping = 29.27;
/*Exchange rate CNY to EURO */
$cny_to_euro = 0.124;
$euro = $cny * $cny_to_euro ;
$price = $euro + $shipping;
$price = number_format($price,2);
$data=array(
'id'=>$post_ID,
'item_number'=>get_post_meta($post->ID, 'scode', true),
'name'=>$post->post_title,
'price'=>$price,
'options_1'=>get_post_meta($post->ID, 'variations', true),
'shipped'=>'1',
);
$where = array("id" => $post_ID);
// Possible format values: %s as string; %d as decimal number; and %f as float.
$format=array( '%d', '%s', '%s', '%s', '%s', '%d');
$where_format = array( '%d' );
if($id>0){
// update
$wpdb->update( $tablename,$data, $where, $format, $where_format);
}else{
// insert
$wpdb->insert( $tablename,$data,$format);
}
AddMetaPrice ( $post_ID ) ;
}
return $post_ID;
}
function AddMetaPrice ( $post_ID )
{
// init
global $post,$wpdb;
// We add the wordpress post ID and price to a meta tag
$metaKey = "product_price" ;
$tableName = "wp_cart66_products" ;
$metaQuery = "SELECT price FROM $tableName WHERE id='$post_ID'" ;
$metaValue = $wpdb->get_var( $metaQuery ) ;
$tableName = "wp_postmeta" ;
// Do we have this post already?
if ( $id > 0 )
{
// this already exists. we only need to update
// $metaQuery = "UPDATE $tableName SET meta_value='$metaValue' WHERE meta_key='$metaKey' AND post_id='$id'" ; // we use wordpress's method instead
$data = array ( "meta_value" => $metaValue ) ;
$where = array ( "meta_key" => $metaKey, "post_id" => $post_ID ) ;
$wpdb->update( $tableName, $data, $where ) ;
}
else
{
// this is not created, we need to create it now (insert)
// $metaQuery = "INSERT INTO $tableName (post_id, meta_key, meta_value) VALUES ('$id', '$metaKey', '$metaValue')" ; // we use wordpress's method instead
$data = array ( "post_id" => $post_ID, "meta_key" => $metaKey, "meta_value" => $metaValue ) ;
$wpdb->insert( $tableName, $data ) ;
}
}
add_action('publish_post', 'do_my_stuff');
我在这里读到存在 ON DUPLICATE KEY 语句。但我不确定它是否可以在上面的代码中实现。