0

I want to update a meta value with a specific meta key out of wordpress page. What I want is that, multiplying a meta value with a variable then write the result to another meta value.

for example;

$var=5
meta_key|meta_value
key-1   |10
key-2   |20

the meta_value for the key-1 = 100 (key-2 * $var). I have tried below code to retrieve key-1 but it returns nothing.

require_once("wp-load.php");

function wp_update_value( ) {

global $wpdb;

$mylink = $wpdb->get_results("
                    SELECT $wpdb->postmeta.meta_value
                    FROM $wpdb->postmeta 
                    WHERE $wpdb->postmeta.meta_key = 'key-1'",
                    ARRAY_A);


$array = unserialize($mylink);

return $array;
}

How can I get two meta values by meta keys and update them for all posts?

Berk Koç
  • 15
  • 8

1 Answers1

1

You can do it inside a loop, something like:

<?php
    header('Response: HTTP/1.1 200 OK');
    define('WP_USE_THEMES', false);
    require('../../../../wp-load.php');
    $args = array(
        'posts_per_page' => '-1',
    ); 
    $the_query = new WP_Query( $args );
    $var = 5;
    if ( $the_query->have_posts() ){
        while ( $the_query->have_posts() ) : $the_query->the_post();
            $value = 100 * (get_post_meta(get_the_ID(),'key-2',true) * $var);
            update_post_meta(get_the_ID(), 'key-1', $value);
        endwhile;
    }
?>
esedeerre
  • 111
  • 2
  • thank you for the answer. I got this error; "Fatal error: Unsupported operand types" when I run the code. – Berk Koç Oct 13 '15 at 19:49
  • Try adding third param 'false' to get_post_meta(get_the_ID(),'key-2') -> get_post_meta(get_the_ID(),'key-2',false), otherwise it will return an array :) (I`ve edit the complete code) – esedeerre Oct 14 '15 at 14:50