Update wp_postmeta meta_value of certain meta_key with meta_value of other meta_key if post_ids are the same

I have searched but I can’t make this to work by myself

So to be completely clear I have the WP database where I have meta_keys like these :

Read More
ID ------ POST_ID -------- META_KEY ---- META_VALUE
1  ------   235  -------  book_price ---- 35$
2  ------   256  -------  book_price ---- 65$
3  ------   235  -------  tcp_book_price ---- 0
4  ------   256  -------  tcp_book_price ---- 0

I want the meta_value of tcp_book_price to receive the meta_value from book_price with the same post_id

End Result wished :

ID ------ POST_ID -------- META_KEY ---- META_VALUE
1  ------   235  -------  book_price ---- 35$
2  ------   256  -------  book_price ---- 65$
3  ------   235  -------  tcp_book_price ---- 35$
4  ------   256  -------  tcp_book_price ---- 65$

I have tried UPDATE FROM SELECT but I can’t make it to work..

Thanks in advance

Ok I found the solution by myself with a PHP Script :

<?php

$conn = mysql_connect("localhost", "root", "root");

if (!$conn) {
echo "Impossible de se connecter à la base de données : " . mysql_error();
   exit;
}

if (!mysql_select_db("database_name")) {
   echo "Impossible de sélectionner la base database_name : " . mysql_error();
   exit;
}

$sql = "SELECT `post_id`, `meta_value` FROM `wp_postmeta` WHERE `meta_key` = 'book_price'";

// query the database
$resource = mysql_query($sql);

// loop through the results
while ($result = mysql_fetch_assoc($resource)) {
    // grab the value
    $price = $result['meta_value'];   // you should use quotes here, btw
    $pid = $result['post_id'];   // you should use quotes here, btw

    echo $price;
    echo $pid;

    // make your modifications;
//    ++$nox; // or whatever

    // build the query
    $sql = "UPDATE `wp_postmeta` SET `meta_value` = '$price' WHERE `meta_key` = 'tcp_price' AND `post_id` = '$pid'";


    // run the query
    mysql_query($sql);
}

?>

Related posts

Leave a Reply