0

I am trying to update multiple posts post meta at the same time. I have the following query:

<form action="" method="post">
<?php 

$variations = new WP_Query();   
$variations->query(array('showposts' => -1, 'post_type' => 'product_variation' )); while ($variations->have_posts()) : $variations->the_post(); ?>

<input name="regular_price[]" type="text" value="<?php echo get_post_meta(get_the_id(), "_regular_price", true); ?>" />
<input name="sale_price[]" type="text" value="<?php echo get_post_meta(get_the_id(), "_sale_price", true); ?>" />
<input name="item_id[]" type="hidden" value="<?php echo get_the_id(); ?>" />

<?php endwhile; wp_reset_query();?> 
<input name="save" type="submit" />

I then have the following php to process the data:

<?php
if (isset($_POST['save'])) {

    $ids = $_POST['item_id'];
    $sales = $_POST['sale_price'];

foreach ($ids as $id){

    update_post_meta($id,'_sale_price',$sale));

}
} ?> 

For some reason the above does not save correctly. It will only save the last value, and apply this to all post meta. Is there something i am doing wrong?

1

This is because there is no relationship between the item id and the price when you are collecting the posted data. Do the changes as below.

Change the sale_price to below to include the item id

<input name="sale_price[<?php echo get_the_id(); ?>]" type="text" value="<?php echo get_post_meta(get_the_id(), "_sale_price", true); ?>" />

Then change the loop for collecting the data as below.

foreach ($ids as $id){
    update_post_meta($id,'_sale_price', $sales[$id]);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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