私は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 ステートメントが存在することをここで読みました。しかし、上記のコードで実装できるかどうかはわかりません。