i have a product listing website, all products are uploaded from csv. i have a two custom field named "old_price" and "new_price".

Sometimes there is no discount (new_price) , so the field be empty. i would like to store the value of "old_price" in "new_price" , If "new_price" is empty.

its important that it get stored in database automatically, No alternate Solution please.

thanks in advance.


1 Answer 1


Assuming your products are custom posts you can do it like this:

add_action('wp_insert_post', 'do_stuff'); // when product is created
add_action('save_post', 'do_stuff' ); // on product update
   function do_stuff( $post_id ) {

       // Making sure this runs only for products
       $slug = 'product_post';
       if ( $slug != $_POST['post_type'] ) {

       if (!get_post_meta( $post_id, 'new_price', true )){
          $old_price = get_post_meta( $post_id, 'old_price', true );
          update_post_meta($post_id, 'new_price', $old_price);    


Update old products

Let's update them by 50.

// url: site.com/test-page?offset=0, change this by 50 (0,50,100,150,200,250...)

$offset = $_GET['offset']; // start with 0
$args = [
         'offset'         => $offset,
         'posts_per_page' => 50, 
         'post_type'      => 'product_post'

$the_query = new WP_Query( $args );

   foreach($the_query->posts as $product){

      if (!get_post_meta( $product->ID, 'new_price', true )){
         $old_price = get_post_meta( $product->ID, 'old_price', true );
         update_post_meta($product->ID, 'new_price', $old_price);    


   echo 'Done!';
  • will this update the old post also. Aug 30, 2014 at 17:44
  • You mean the old_price?
    – Stubbies
    Aug 30, 2014 at 18:02
  • No, old post (products) which i have created before. will this function update its "new_price" too. Aug 30, 2014 at 18:10
  • No, this runs when a product is created or updated. To change old products you can just update them with batches. I'll update my answer.
    – Stubbies
    Aug 30, 2014 at 19:31
  • thank you lot, its simple and does the job perfectly..thanks once again. Aug 30, 2014 at 20:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.